php - 获取对按键搜索的php数组元素的引用
问题描述
我有以下php数组结构:
$r = [
[
'id' => 'abc',
'children' => [
[
'id' => 'def',
'children' => []
],
[
'id' => 'ghi',
'children' => [
[
'id' => 'jkl',
'children' => []
],
[
'id' => 'mno',
'children' => []
]
]
]
]
]
]
以及搜索父母的功能,例如:
function &getElementByUuid($element, $uuid){
foreach($element as $child){
if($child['id'] == $uuid){
return $child;
}
if(isset($child['children'])){
if($childFound = $this->getElementByUuid($child['children'], $uuid)){
return $childFound;
}
}
}
return false;
}
通过调用这个
getElementByUuid($r, 'ghi');
搜索已经很完美了,因为它返回元素的父元素,我想添加子元素。
但我需要将找到的父数组元素作为参考,以便向它添加数组元素。
像:
$parent = getElementByUuid($r, 'ghi');
$parent['children'][] = [
'id' => 'xyz',
'children' => []
];
但是我无法将父元素作为参考,尽管我用 & 标记了该方法以返回参考,而不是值。
对此的任何帮助都会很棒。
提前致谢 :)
解决方案
您也需要通过引用遍历数组并在调用函数之前添加 & 符号。这是一个小例子,如何通过引用返回:https ://3v4l.org/7seON
<?php
$ar = [1,2,3,4];
function &refS(&$ar, $v) {
foreach ($ar as &$i) {
if ($i === $v) {
return $i;
}
}
}
$x = &refS($ar, 2);
var_dump($x);
$x = 22;
var_dump($ar);
推荐阅读
- r - Xaringan 模块演示
- python - 如何根据字典对列表中的单词进行分类?
- spring - 当我有两种类型的用户时,如何使用 spring security 保护 rest api
- java - 为什么除以 1000000000 时没有小数位
- c# - 使用自动身份验证将登录用户重定向到新网站
- tensorflow - 扁平化输入层形状
- python - Matplotlib中的散点图Y轴数字范围问题
- django - Django中类别帖子的问题分页
- amazon-web-services - 使用 apache camel 从 DynamoDB 中检索项目
- javascript - 如何在 javascript 上使用颜色图