1

I have the following array:

$array = array('23' => array('19' => array('7' => array('id' => 7, 'name' => 'John Doe'))));

Array
(
    [23] => Array
        (
            [19] => Array
                (
                    [7] => Array
                        (
                            [id] => 7
                            [name] => John Doe
                        )

                )

        )

)

I want to access sub-element and i know his sub keys that 23 19 7. I can do this with simple format

echo $array['23']['19']['7']['name']; // John Doe

But these array have just 3 level and this may vary, more or less. I have to make an array unlimited level.

I tried that like i want with following codes:

$keys =  array('23', '19', '7');

echo $array[$keys]['name'];

And of course i got Warning: Illegal offset type in error.

Then i tried this one but i couldnt get any element:

function brackets($str) {
    return sprintf("['%s']", $str);
}

$keys =  array('23', '19', '7');
$string_key = implode('', array_map('brackets', $keys)); // ['23']['19']['7']

echo $array{$string_key}['name'];

2 Answers 2

1

You can make a function that you can call with a key-array.

function getArrayPathVal($arr, $path){

    if(!is_array($path))
        return $arr[$path];

    $curr = $arr;
    foreach($path as $key)
    {
        if(!$curr[$key])
            return false;

        $curr = $curr[$key];
    }

    return $curr;
}


$array = array('23' => array('19' => array('7' => array('id' => 7, 'name' => 'John Doe'))));
$keys =  array('23', '19', '7');

$res = getArrayPathVal($array, $keys);
print $res['name']; //Prints 'John Doe'
Sign up to request clarification or add additional context in comments.

Comments

1

You could try a recursive function:

function getByKeys ($arr, $keys) {
  if (count($keys) == 0)
    return $arr;
  $key = array_shift ($keys);
  return getByKeys ($arr[$key], $keys);
}

$array = array('23' => array('19' => array('7' => array('id' => 7, 'name' => 'John Doe'))));
echo getByKeys ($array, array('23', '19', '7'));

this is untested, but the concept should do the trick:

  1. retrieve the next key to be applied to the array
  2. next iteration using the sub-array denoted by that key
  3. stop if no more keys should be applied.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.