onassar
onassar

Reputation: 3558

access php array children through parameters?

I have a unique case where I have an array like so:

$a = array('a' => array('b' => array('c' => 'woohoo!')));

I want to access values of the array in a manner like this:

So basically, it drills down in the array using the passed in variables in the second param and checks for the existence of that key in the result. Any ideas on some native php functions that can help do this? I'm assuming it'll need to make use of recursion. Any thoughts would be really appreciated.

Thanks.

Upvotes: 0

Views: 327

Answers (4)

Gumbo
Gumbo

Reputation: 655239

Here’s a recursive implementation:

function some_function($array, $path) {
    if (!count($path)) {
        return;
    }
    $key = array_shift($path);
    if (!array_key_exists($key, $array)) {
        return;
    }
    if (count($path) > 1) {
        return some_function($array[$key], $path);
    } else {
        return $array[$key];
    }
}

And an iterative implementation:

function some_function($array, $path) {
    if (!count($path)) {
        return;
    }
    $tmp = &$array;
    foreach ($path as $key) {
        if (!array_key_exists($key, $tmp)) {
            return;
        }
        $tmp = &$tmp[$key];
    }
    return $tmp;
}

These functions will return null if the path is not valid.

Upvotes: 2

Corey Ballou
Corey Ballou

Reputation: 43457

This is untested but you shouldn't need recursion to handle this case:

function getValueByKey($array, $key) {
    foreach ($key as $val) {
        if (!empty($array[$val])) {
            $array = $array[$val];
        } else return false;
    }
    return $array;
}

Upvotes: 2

Gordon
Gordon

Reputation: 316969

You could try with RecursiveArrayIterator

Here is an example on how to use it.

Upvotes: 2

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124768

$a['a'] returns the array at position a.
$a['a']['b']['c'] returns woohoo.

Won't this do?

Upvotes: 1

Related Questions