Home > Software design >  Search a nested array and return the parent array?
Search a nested array and return the parent array?

Time:11-29

$array = [
    [
        'name' => 'john',
        'age' => 25
        'children' => [
            'jane',
            'jeff',
        ],
    ],
    ....
];

I wish to get the entire sub array depending on a value in a nested array, for example, I can do...

array_search('john', array_column($array, 'name')); // 0

But how can I do the same for the children sub array, for example, I want to find the john multidimensional array by searching for a child's name, e.g. jeff

CodePudding user response:

Only the array_search function alone will probably not be enough. The combination array_search and array_filter would help you

array_filter($array, function($value) {
   return ($value['name'] === 'john' && in_array('jeff', $value['children']));
});
  •  Tags:  
  • php
  • Related