Home > Blockchain >  How to filter deep array?
How to filter deep array?

Time:10-05

I have this array:

$test = [
    ['teams' => ['home' => 'Lazio']],
    ['teams' => ['away' => 'Inter']]
];

I need to search Inter, so I did:

$key = array_search('Inter', array_column($test, 'teams'));
var_dump($test[$key]);

but it returns false as $key.

CodePudding user response:

array_search() doesn't search nested arrays. There's no built-in functionthat does this, so just use a loop.

$key == null;
foreach (array_column($test, 'teams') as $i => $teams) {
    if (in_array('Inter', $teams)) {
        $key = $i;
        break;
    }
}
if ($key !== null) {
    var_dump($test[$key]);
}

CodePudding user response:

$needle = array_flip(['Inter']);
$result = array_filter(array_column($test, 'teams'), function(array $item) use ($needle) {
    return array_intersect_key(array_flip($item), $needle);
});

using $needle as an array (and as result array_intersect_key) just in case you need to find more than one value.

You can change array_intersect_key to isset and single $needle value (instead of array).

also, is better to avoid using the array_search, (also in_array) functions for big arrays because of their complexity of algorithm (eq low performance)

CodePudding user response:

I'm bored. You can filter out non-matching items and then get the key. You can search for it anywhere in the array without specifying home, away or other:

$key = key(array_filter($test, function($v) { return in_array('Inter', $v['teams']); }));

Not the preferred way, but if there is only home and away you can search using an array:

($key = array_search(['away' => 'Inter'], array_column($test, 'teams'))) || 
($key = array_search(['home' => 'Inter'], array_column($test, 'teams')));

Or with one array_column call:

($t = array_column($test, 'teams')) && ($key = array_search(['away' => 'Inter'], $t)) || 
                                       ($key = array_search(['home' => 'Inter'], $t));

All of the code above returns the key of the first match.

  •  Tags:  
  • php
  • Related