【发布时间】:2021-06-28 16:52:20
【问题描述】:
给定以下多维数组:
$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],
],
],
],
],
],
];
有没有办法将'p's 中的所有值作为数组唯一地获取?
输出应该是[1, 2, 9, 3, 4, 10, 5, 6, 7, 8]
我尝试了一个简单的单行,但它只适用于第一级(A、B、C),嵌套的$items 被忽略:
$ps = array_unique(call_user_func_array('array_merge', array_column($menu['root']['items'], 'p')));
print_r($ps);
我也尝试写一个递归函数,但我完全卡住了,输出不是预期的
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);
请帮忙?
【问题讨论】:
-
你得到的输出是什么?