1

I have the following:

$values = Array (
          ['level1'] => Array (
             ['level2'] => Array(
                 ['level3'] => 'Value'
                 )
              )
          )

I also have an array of keys:

$keys = Array (
          [0] => 'level1',
          [1] => 'level2',
          [2] => 'level3'
        )

I want to be able to use the $keys array so I can come up with: $values['level1']['level2']['level3']. The number of levels and key names will change so I need a solution that will read my $keys array and then loop through $values until I get the end value.

Mr.SCW
  • 11
  • 4
  • 1
    Okay, I think I understood the problem. Where is your attempt? – Aniket Sahrawat Mar 02 '18 at 18:18
  • Please, don't forget to close your question if an anwser solves your problem :) Thanks! https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235 – Syscall Mar 04 '18 at 23:08

2 Answers2

1

You could iterate over $values and store a $ref like this :

$ref = $values ;
foreach ($keys as $key) {
    if (isset($ref[$key])) {
        $ref = $ref[$key];
    }
}
echo $ref ; // Value

You also could use references (&) to avoid copy of arrays :

$ref = &$values ;
foreach ($keys as &$key) {
    if (isset($ref[$key])) {
        $ref = &$ref[$key];
    }
}
echo $ref ;
Syscall
  • 19,327
  • 10
  • 37
  • 52
0
<?php

$values['level1']['level2']['level3'] = 'Value';
$keys = array (
          0 => 'level1',
          1 => 'level2',
          2 => 'level3'
        );


$vtemp = $values;

foreach ($keys as $key) {

    try {
        $vtemp = $vtemp[$key];
        print_r($vtemp);
        print("<br/>---<br/>");
    }
    catch (Exception $e) {
        print("Exception $e");  
    }

}

Hope this helps. Of course remove the print statements but I tried it and in the end it reaches the value. Until it reaches the values it keeps hitting arrays, one level deeper at a time.

rishijd
  • 1,294
  • 4
  • 15
  • 32