Given the following multidimensional array:
$menu = [
'root' => [
'items' => [
'A' => [
'p' => [1, 2, 9],
],
'B' => [
'p' => [1, 2, 3, 9],
],
'C' => [
'p' => [1, 2, 4, 9],
],
'D' => [
'items' => [
'D1' => [
'p' => [1, 2, 3, 4, 9],
],
'D2' => [
'p' => [1, 2, 3, 4],
],
],
],
'E' => [
'items' => [
'E1' => [
'p' => [1, 2, 10],
],
],
],
'F' => [
'items' => [
'F1' => [
'p' => [5, 6],
],
'F2' => [
'p' => [7, 8],
],
],
],
],
],
];
Is there a way to get all the values in the 'p's as array, uniquely?
The output should be [1, 2, 9, 3, 4, 10, 5, 6, 7, 8]
I tried a simple one-liner, but it works only for the first level (A, B, C), nested $items are ignored:
$ps = array_unique(call_user_func_array('array_merge', array_column($menu['root']['items'], 'p')));
print_r($ps);
I also tried to write a recursive function, but I get totally stuck and the output is not what's expected
function recursive_ps($elem, $arr = []){
$output = $arr;
if (isset($elem['items'])){
foreach($elem['items'] as $key => $value){
if (isset($value['p'])){
$output = array_merge($arr, $value['p']);
if (isset($value['items'])){
return recursive_ps($value, $output);
}
}
}
}
return $output;
}
$o = recursive_ps($menu['root']);
print_r($o);
Please, any help?