0

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.

Hayden Schiff
  • 3,280
  • 19
  • 41
  • *I want $keys to be of arbitrary length.* means that you must have those indices in `$arr`, right? – Mubin Nov 02 '15 at 22:51
  • Uh yeah, we can assume that all the indices I have in `$keys` will indeed exist in `$arr`. – Hayden Schiff Nov 02 '15 at 22:51
  • $keys has any number of elements, but the $arr will always be 3 dimensional? And you always want to get data from 3 dimensions, or less/more? – Steven Scott Nov 02 '15 at 22:52
  • and also, how many dimensions does your `$arr` has? – Mubin Nov 02 '15 at 22:53
  • `$arr` will be N-dimensional, and `$keys` will be of length N or less. I don't know what N is in advance. I'm thinking now that the solution to this is probably recursive, I might actually have an idea of the answer.... – Hayden Schiff Nov 02 '15 at 22:53
  • @oxguy3 I think you are right, the recursive call is the way to do it. – Steven Scott Nov 02 '15 at 22:58

1 Answers1

1

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);
}
Hayden Schiff
  • 3,280
  • 19
  • 41