This question already has an answer here:
Okay, say I have an array, $arr
. I want to access $arr['a']['b']['c']...
. And I have another array, $keys
, that looks like this: ['a', 'b', 'c', ...]
. How can I use $keys
as the identifiers to access the sub element of $arr
?
In other words, I basically want to do something along the lines of this: $arr[$keys[0]][$keys[1]][$keys[2]]
. Except, in that example, I hardcoded it to work only if $keys
has exactly three elements; that's no good, I want $keys
to be of arbitrary length.
If I've successfully explained what I'm trying to do, can someone tell me if it's possible? Muchas gracias.
</div>
I think I figured it out. Figures the solution would be recursive. Here's what I came up with (untested as of yet but in my head I'm pretty sure it's right):
public function getDeepElement($arr, $keys) {
if (count($keys) == 0) { // base case if $keys is empty
return $arr;
}
if (count($keys) == 1) { // base case if there's one key left
return $arr[$keys[0]];
}
$lastKey = array_pop($keys); // remove last element from $keys
$subarr = $arr[$lastKey]; // go down a level in $arr
return getDeepElement($subarr, $keys);
}