I have an array of arrays,
I have posted the essential structure below,
The recursion can be of any depth.
Anyway, what I want to do is, loop over every item in the array, and if it’s ['item']->data('id') value is equal to $id then remove that section of the tree,
But I am not sure as to the most efficient way of doing this?
I think this might work, but am I missing something?
function removeKey($key, &$categories){
foreach($categories as $k => $category){
if($category['item']->data('id') == $key){
unset($categories[$k]);
return;
}
if(!empty($category['children']))
removeKey($key, $category['children']);
}
}
removeKey($id, $categories);
array(
array(
'item' => "category Object", //use ->data('id') to get the id!
'children' => array(
array(
'item' => "category Object",
'children' => array(
array(
'item' => "category Object",
'children' => array()
)
)
),
array(
'item' => "category Object",
'children' => array(
array(
'item' => "category Object",
'children' => array()
)
)
)
)
),
array(
'item' => "category Object",
'children' => array(
array(
'item' => "category Object",
'children' => array(
array(
'item' => "category Object",
'children' => array()
)
)
),
array(
'item' => "category Object",
'children' => array(
array(
'item' => "category Object",
'children' => array()
)
)
)
)
)
);
you can use either array_map or array_filter to traverse each child and unset the desired one.