Searching for a key in a multidimensional array then changing a value with PHP(在多维数组中搜索一个键,然后用 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
这篇关于在多维数组中搜索一个键,然后用 PHP 更改一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在多维数组中搜索一个键,然后用 PHP 更改一个值
基础教程推荐
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01