我有一个看起来像的多维数组
[0] => Array
(
[recordId] => 5
[leaf] => 1
[children] => Array
(
[0] => Array
(
[recordId] => 6
[leaf] => 1
[children] => Array
(
[0] => Array
(
[recordId] => 7
[leaf] => 1
)
)
)
[1] => Array
(
[recordId] => 8
[leaf] => 1
[children] => Array
(
[0] => Array
(
[recordId] => 9
[leaf] => 1
)
[1] => Array
(
[recordId] => 10
[leaf] => 1
)
)
)
)
)
每个节点都有一个默认为TRUE的"leaf"键,如果还有其他节点,则有一个"children"数组。
如果节点中包含"children"数组,则需要将"leaf"键值设置为FALSE。这样,只有最终节点具有lead=TRUE指定。
我试过搜索,但找不到能满足我需要的代码,我也无法理解我认为需要的递归函数。
有什么想法可以用PHP实现吗?
谢谢你的帮助。
理论上这应该有效:
function findChild(&$array){
foreach($array as &$arr){
if(isset($arr['children'])){
$arr['leaf'] = 0; //there are children
findChild($arr['children']);
}
else {
$arr['leaf'] = 1; //there are no children
}
}
}
以下是一个工作演示:http://codepad.org/AnYiRpES
实际上很简单:
function leafOrNotLeaf(array $array) {
foreach ($array as $key => $sub) {
if (isset($sub['children'])) {
$array[$key]['leaf'] = false;
$array[$key]['children'] = leafOrNotLeaf($sub['children']);
}
}
return $array;
}
$new_array = leafOrNotLeaf($array);
在实际$array
:上行走
array_walk($array, $walker = function (&$node) use (&$walker) {
$node['leaf'] = (int) empty($node['children'])
OR array_walk($node['children'], $walker);
});
可能有点神秘,所以你一定喜欢PHP。