I am trying to create an single-dimension array of ‘id’s’ extracted from a multidimensional array that will vary in depth. I need to extract the value from EACH array (no matter how deep). Each array has been indexed (see below) with the same keys. I have tried flattening so I could use ‘array_column’ (doesn’t work because of the number of keys in each array), as well as methods like print_r(array_keys($data[0])[0]) (doesn’t work for unknown dimension depth). It seems simple enough but I’m not finding any examples that are like this. Any direction is appreciated. Thank you.
Array
(
[0] => Array
(
[id] => 1000005
[first_name] => James
[last_name] => Smith
[position_root] => CHF CUST EX
[position_area] => Customer Operations
[items] => Array
(
[0] => Array
(
[id] => 1000134
[first_name] => Brandt
[last_name] => Jones
[position_root] => BS APL PJCTS
[position_area] => Customer Executive Support
[items] => Array
(
)
)
[1] => Array
(
[id] => 1000149
[first_name] => Daniel
[last_name] => Brown
[position_root] => CUST PROG
[position_area] => CUSTOMER PROGRAMS
[items] => Array
(
[0] => Array
(
[id] => 1000060
[first_name] => Duane
[last_name] => Pearson
[position_root] => CUST PRG IN
[position_area] => Customer Program Design
[items] => Array
(
)
)
What I am hoping for is:
[0] => 1000005 [1] => 1000134 [2] => 1000149 [3] => 1000060
… and so on …
Advertisement
Answer
As suggested, you can use array_walk_recursive to achieve this.
<?php
$ids = [];
array_walk_recursive($data,function($value,$key) use (&$ids){
if($key == 'id') $ids[] = $value;
});
print_r($ids);