Wyszukiwanie rekurencyjne i usuwanie w tablicy?
Pracuję z tablicą wielowymiarową, którą chcę móc usunąć tablicę (i wszystkie dzieci), które pasują do identyfikatora.
Funkcja, którą wypróbowałem, to:
function removeKey($key, $array, $childKey = 'children'){
if(isset($array[$key])){
unset($array[$key]);
return $array;
}
foreach($array as &$item)
if(isset($item[$childKey]))
$item = removeKey($key, $item[$childKey], $childKey);
return $array;
}
Moja przykładowa tablica to:
Array
(
[5] => Array
(
[id] => 5
[parent_id] =>
[menu_title] => Drinks
[page_title] => Drinks
[status] => 1
[products] => 0
)
[1] => Array
(
[id] => 1
[parent_id] =>
[menu_title] => Electronics
[page_title] => Electronics
[status] => 1
[products] => 0
[children] => Array
(
[2] => Array
(
[id] => 2
[parent_id] => 1
[menu_title] => Computers
[page_title] => Computers
[status] => 1
[products] => 0
[children] => Array
(
[4] => Array
(
[id] => 4
[parent_id] => 2
[menu_title] => Apple
[page_title] => Apple - Imacs and Macbooks
[status] => 1
[products] => 0
)
)
)
[3] => Array
(
[id] => 3
[parent_id] => 1
[menu_title] => Mobile Phones
[page_title] => Mobile Phones
[status] => 1
[products] => 0
)
)
)
)
i wynik, którego szukam (wywołanie funkcji za pomocą(2, $array, 'children')
) jest:
Array
(
[5] => Array
(
[id] => 5
[parent_id] =>
[menu_title] => Drinks
[page_title] => Drinks
[status] => 1
[products] => 0
)
[1] => Array
(
[id] => 1
[parent_id] =>
[menu_title] => Electronics
[page_title] => Electronics
[status] => 1
[products] => 0
[children] => Array
(
[3] => Array
(
[id] => 3
[parent_id] => 1
[menu_title] => Mobile Phones
[page_title] => Mobile Phones
[status] => 1
[products] => 0
)
)
)
)
ale otrzymuję wynik
Array
(
[5] => Array
(
[id] => 5
[parent_id] =>
[menu_title] => Drinks
[page_title] => Drinks
[status] => 1
[products] => 0
)
[1] => Array
(
[3] => Array
(
[id] => 3
[parent_id] => 1
[menu_title] => Mobile Phones
[page_title] => Mobile Phones
[status] => 1
[products] => 0
)
)
)
Nie mam pojęcia, co tu się dzieje!