I have two arrays of arrays that have the keys 'menu_title' and 'id'.
I want to go through the two arrays and store in a third array the id of any arrays in the first array that shares a 'menu_title' with an array in the second array.
I know I can do it like so:
$collision = [];
foreach($children as $child)
foreach($siblings as $sibling)
if($child['menu_title'] == $sibling['menu_title'])
$collision[] = $child['id'];
But that means I am looping over the second array for every single item in the first.
Perhaps this would be better?
$collision = [];
foreach($siblings as &$sibling)
$sibling = $sibling['menu_title'];
foreach($children as $child)
if(in_array($child['menu_title'], $siblings))
$collision[] = $child['id'];
But I still think there must be a better way?
update
The arrays are populated by sql, basically if I delete a category then I move the children categories up to the same level as the category I am deleting.
But If any of the children have the same menu_title as one of the deleting categories siblings then I need to rename the menu_title of the child to "whatever-1" e.g. "computers-1"
So I am building an array of id's I need to update and then I will do an sql update on those ID's possibly there is an enhancement to be made to how I am approaching this?
Update
So, in the end I ended up with:
$id = 4;
$category = $this->categoryeditormodel->getCategory($id);
$children = $this->categoryeditormodel->getChildCategories($id);
$siblings = $this->categoryeditormodel->getSiblingCategories($id);
foreach($siblings as &$sibling)
$sibling = $sibling['menu_title'];
foreach($children as &$child){
$child['parent_id'] = $category['parent_id'];
if(in_array($child['menu_title'], $siblings)){
$i = 0;
while(in_array(($name = ($child['menu_title'].'-'.++$i)), $siblings));
$child['menu_title'] = $name;
}
}
$this->categoryeditormodel->update_batch($children);
The three functions at the top do what they say, but they are cheap as the categories are already loaded into a cache so it is not another sql query.
and update_batch is simply a shortcut to Code Igniters update_batch function but it passes through the table name and the id key.
any thoughts?