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.

6
  • I want $keys to be of arbitrary length. means that you must have those indices in $arr, right? Commented Nov 2, 2015 at 22:51
  • Uh yeah, we can assume that all the indices I have in $keys will indeed exist in $arr. Commented Nov 2, 2015 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? Commented Nov 2, 2015 at 22:52
  • and also, how many dimensions does your $arr has? Commented Nov 2, 2015 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.... Commented Nov 2, 2015 at 22:53

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.