PHP - Getting Value of Nested Array from Array of Keys

故事扮演 提交于 2019-12-24 15:24:25

问题


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.


回答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 ;



回答2:


<?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.



来源:https://stackoverflow.com/questions/49074943/php-getting-value-of-nested-array-from-array-of-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!