I have following multidimensional array :
Array
(
[entity_id] => 5740
[parent_id] => 5739
[label] => Sports
[name] => sports
[icon] => http://localhost/magento/media/catalog/category/
[level] => 3
[tab_id] => Array
(
[0] =>
)
[color] => #555555
[coordinate] => Array
(
[0] =>
)
[amount] => 100000
[children] => Array
(
[0] => Array
(
[entity_id] => 5754
[parent_id] => 5740
[label] => Badminton
[name] => badminton
[icon] => http://localhost/magento/media/catalog/category/
[level] => 4
[tab_id] => Array
(
[0] => 354
)
[color] => #DACC5C
[coordinate] => Array
(
[0] => 12.9539974,77.6309395
)
[amount] => 75000
[children] => Array
(
[0] => Array
(
[entity_id] => 5756
[parent_id] => 5754
[label] => Tournaments
[name] => tournaments
[icon] => http://localhost/magento/media/catalog/category/
[level] => 5
[tab_id] => Array
(
[0] => 354
)
[color] => #8DCD55
[coordinate] => Array
(
[0] => 12.9539974,77.6309395
)
[amount] => 42187.5
)
)
)
How can I perform array search on this to get the sought children array. I have a dynamic value on the basis of which I want to search.
Let's say I want to search for [label] => Badminton
, how I can get that array?
Try this:
function search_recursive(array $children, $key, $value){
foreach($children as $child){
if(isset($child[$key]) && $child[$key] === $value){
return $child;
}
if(isset($child['children']) && is_array($child['children'])){
$found = search_recursive($child['children'], $key, $value);
if($found){
return $found;
}
}
}
return false;
}
$children = [$array];
$result = search_recursive($children, 'label', 'Badminton');