海先看看这个数组,
Array
(
[0] => Array
(
[id] => 4
[parent_id] => 3
[children] => Array
(
[0] => Array
(
[id] => 7
[parent_id] => 4
[children] => Array
(
[0] => Array
(
[id] => 6
[parent_id] => 7
[children] => Array
(
[0] => Array
(
[id] => 2
[parent_id] => 6
)
)
)
)
)
)
)
[1] => Array
(
[id] => 5
[parent_id] => 3
)
)
我需要所有id的输出[IE:4,7,6,2,5]是期望的结果 我需要
之类的东西foreach ($tree as $j) {
echo $j['id'];
if($j['children']){
}
但是如何循环获取所有孩子的?我无法捕获所有子元素,否则我将被无限循环撞击,如何在php中获得所需的结果?任何建议将不胜感激!
答案 0 :(得分:6)
应该执行以下操作:
$result = [];
array_walk_recursive($input, function($value, $key) use(&$result) {
if ($key === 'id') {
$result[] = $value;
}
});
答案 1 :(得分:1)
您必须使用以下递归函数:
function getIds($tree) {
foreach ($tree as $j) {
echo $j['id'];
if(isset($j['children'])){
getIds($j['children']);
}
}
}
主要需要的是:
getIds($tree);