views:

57

answers:

1

Hi guys,
So I have a function as detailed below,
I believe it is too long and can be shortened.
I think I have fallen over in the array manipulation part.
Please ignore the strange database syntax


So basically this function is given a string like this

abc, def, ghi, jkl, mno

due to some glitches it can be received with an extra , so it ends up as

abc, def, ghi, jkl, mno,

The function must convert the string so it looks like

'abc', 'def', 'ghi', 'jkl', 'mno' ($groups)

The string is then used in a select query

SELECT group_name as name FROM contact_groups WHERE group_name IN($groups);

We use array_diff() on the original array and the array from the select query.
This will give us an array of all the groups that we are using that do not exist. ($create)

Next we Loop over the array and create the groups

foreach($create as $group){
  $values = array(
    'user_id', $_SESSION['user_id'],
    'group_name', $group
  );
  $this->database->insert_query($values, 'contact_groups');
}

Now we do the select query again, but this time we do it to get the id's of the groups

SELECT group_id as id FROM contact_groups WHERE group_name IN($groups);

And finally we loop over the group id's and add them to another table.


private function groups($groups){
  $groups = split(', ', $groups);
  $intersect = array();
  $db_rows = array();

  foreach($groups as &$group)
    $group = trim(str_replace (',', '', $group)); //remove any rogue spaces or commas

  $groupsq = $groups;
  foreach($groupsq as &$group)
    $group = '\''.$group.'\'';

  $groupsq = implode(', ', $groupsq);
  $q = "SELECT group_name as name FROM contact_groups WHERE group_name IN($groupsq);";
  $r = $this->database->results($this->database->query($q));
  while($row = mysql_fetch_assoc($r)) {
    $intersect[] = $row;
  }

  //create a list of non-existent groups
  $create = array_diff($groups, $intersect);

  foreach($create as $group){
    $values = array(
      'user_id', $_SESSION['user_id'],
      'group_name', $group
    );

    $this->database->insert_query($values, 'contact_groups');
    $this->database->query($q);
  }

  $q = "SELECT group_id as id FROM contact_groups WHERE group_name IN($groupsq);";
  $r = $this->database->results($this->database->query($q));
  while($row = mysql_fetch_assoc($r)) {
    $db_rows = $row;
  }

  foreach($db_rows as $group){
    $values = array(
      'group_id' => $group,
      'contact_id' => $this->contact_id
    );

    $q = $this->database->insert_query($values, 'contact_groups_link');
    $this->database->query($q);
  }
}
A: 

Well, a much shorter function for the first few steps is:

/**
 @param string like bla, bla, bla, bla,
 @return string like "bla", "bla", "bla"
*/
function blablabla($string){
    return rtrim(preg_replace('/([a-z]+)/', '"\1"', $string), ',');   
}

As of the rest of your code, I'm not really sure what you're trying to do.

cypher