php :: shorten this function? :: array manipulation

cokeelitevb

New Member
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 syntaxSo basically this function is given a string like this \[quote\] abc, def, ghi, jkl, mno\[/quote\]due to some glitches it can be received with an extra \[code\],\[/code\] so it ends up as \[quote\] abc, def, ghi, jkl, mno, \[/quote\]The function must convert the string so it looks like\[quote\] 'abc', 'def', 'ghi', 'jkl', 'mno' ($groups)\[/quote\]The string is then used in a select query\[quote\] SELECT group_name as name FROM contact_groups WHERE group_name IN($groups);\[/quote\]We use \[code\]array_diff()\[/code\] 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\[code\]foreach($create as $group){ $values = array( 'user_id', $_SESSION['user_id'], 'group_name', $group ); $this->database->insert_query($values, 'contact_groups');}\[/code\]Now we do the select query again, but this time we do it to get the id's of the groups\[quote\] SELECT group_id as id FROM contact_groups WHERE group_name IN($groups);\[/quote\]And finally we loop over the group id's and add them to another table.\[code\]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); }}\[/code\]
 
Back
Top