首页 > 解决方案 > 获取对按键搜索的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' => []
];

但是我无法将父元素作为参考,尽管我用 & 标记了该方法以返回参考,而不是值。

对此的任何帮助都会很棒。

提前致谢 :)

标签: phparrayssearchreference

解决方案


您也需要通过引用遍历数组并在调用函数之前添加 & 符号。这是一个小例子,如何通过引用返回: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);

推荐阅读