获取对按键搜索的php数组元素的引用

时间:2019-05-17 09:44:07

标签: php arrays search reference

我具有以下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' => []
];

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

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

预先感谢:)

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我只是个愚蠢的人...

致电:

$parent =& $this->getElementByUuid($tree, $parentId);

和方法应如下所示:

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;
}

否则,php将创建值的副本并迭代这些值,返回对副本的引用,而不是对引用的引用。

我希望这可以对其他人有所帮助;)