I am trying to filter an array
$array = [ [ 'id' => 1, 'some_key' => 'some_value', 'attribute' => [ 'id' => 45, 'cat_id' => 1 ], 'sub' => [ 'id' => 17, 'some_key' => 'some_value', 'attribute' => [ 'id' => 47, 'cat_id' => 17 ], ], ], [ 'id' => 2, 'some_key' => 'some_value', 'sub' => [ 'id' => 19, 'some_key' => 'some_value', ], ] ]; $childArray = []; array_walk_recursive($array, static function($value, $key) use(&$childArray){ if($key === 'id') { $childArray[] = $value; } });
This returns me an array of all array-fields having id
as key.
[1,45,17,47,2,19]
But there is a small problem, some of the array have an key called attribute
containing an id
key field that I dont want to have.
[1,17,2,19] //this is what I want
Is there a way to say “don’t take the id inside attribute” ?
My current solution, I added a filter before my filter 😀
/** * @param array $array * @param string $unwanted_key */ private function recursive_unset(&$array, $unwanted_key) { unset($array[$unwanted_key]); foreach ($array as &$value) { if (is_array($value)) { $this->recursive_unset($value, $unwanted_key); } } }
but this seems like this is not the best practice ^^
Advertisement
Answer
You can traverse recursively manually instead of array_walk_recursive
and avoid all under attribute
key.
<?php $childArray = []; function collectIDs($arr,&$childArray){ foreach($arr as $key => $value){ if($key === 'attribute') continue; if(is_array($value)) collectIDs($value,$childArray); else if($key === 'id') $childArray[] = $value; } } collectIDs($array,$childArray); print_r($childArray);
Demo: https://3v4l.org/V6uFf