函数,它接受对数组的引用,搜索数组,并返回对搜索结果的引用


Function that accepts a reference to an array, searches the array, and returns a reference to the search result?

我需要一个函数/类方法,它可以在数组中找到一个元素(借助另一个包含该元素位置的数组)并返回对它的引用。

没用,我试过这样做:

$var = array("foo" => array("bar" => array("bla" => "goal")));
$location = array("foo", "bar", "bla");
...
$ref =& $this->locate($var, $location);
...
private function &locate(&$var, $location) {
    if(count($location))
        $this->locate($var[array_shift($location)], $location);
    else
        return $var;
}

上面的函数成功地找到了"目标",但引用没有返回到$ref,而是$ref为空。

非常感谢任何帮助,这严重阻碍了我完成工作。非常感谢。

您需要将结果传递到递归堆栈中以进行第一个调用:

private function &locate(&$var, $location) {
    if(count($location)) {
        $refIndex= array_shift($location);
        return $this->locate($var[$refIndex], $location);
    } else {
        return $var;
    }
}

我会在递归调用之前进行array_shift调用。你知道,我对函数调用感到不安,因为函数调用中的参数会发生变化。