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

StackOverflow https://stackoverflow.com/questions/8894404

Question

I need a function/class-method that finds an element in an array (with the help of another array containing the location of said element) and returns a reference to it.

To no avail I've tried to do it like so:

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

}

The function above successfully finds the 'goal' but the reference is not returned to $ref, instead $ref is empty.

Any help is greatly appreciated, this is seriously keeping me from completing my work. Thank You.

Était-ce utile?

La solution

You need to pass over the result into the recursion stack to the first call:

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

And I would do the array_shift call before the recursive call. You know, I'm uneasy with function calls where parameters change within the invocation.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top