在多维数组中搜索一个键,然后用 PHP 更改一个值
我有一个像这样的多维数组
I have a multidimensional array that looks like this
[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' 数组.
Each node has a 'leaf' key that is TRUE by default and has a 'children' array if there are further nodes down.
如果节点中包含一个 'children' 数组,我需要将 'leaf' 键值设置为 FALSE.这样,只有最终节点具有叶子 = TRUE 指定.
I need to set the 'leaf' key value to FALSE if there is a 'children' array contained in the node. That way only final nodes have the leaf = TRUE designation.
我尝试过搜索,但找不到代码来执行我需要的操作,而且我无法围绕我认为需要的递归函数.
I've tried searching but can't find code to do what I need and I can't wrap my head around the recursive function that I believe is needed.
有什么想法可以在 PHP 中实现吗?
Any ideas how I could accomplish this in 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
相关文章