开发者

How to get array value dynamically

开发者 https://www.devze.com 2023-03-02 09:01 出处:网络
I\'m not sure if there is such a function, but I\'d expect it to do the following: get_array_value($array, $chain); where $array is the array to search for the value, and $chain is an array that conta

I'm not sure if there is such a function, but I'd expect it to do the following: get_array_value($array, $chain); where $array is the array to search for the value, and $chain is an array that contains information which value to retrieve.

Example usage: if $chain = array('key1', 'key2', 'key3');, then the function should return $array['key1']['key2']['key3'];开发者_如何学Python

Is there anything similar out there already and if not, how could I achieve this?

Thanks in advance!

UPDATE:

Huh, the intended result should be a single value, not an array. So I could use it like echo get_array_value($array, $chain);


$cloneArray = $array;  // clone it for future usage
foreach($chain as $value)
{
   $cloneArray =  $cloneArray[$value];
}

var_dump($cloneArray);


function resolve ($array, $chain) {
    return empty($chain) 
        ? $array;
        :resolve($array[array_shift($chain)], $chain);
}

Thats the very short form. You must verify, that all keys, that you want to resolve, exists (and such).

0

精彩评论

暂无评论...
验证码 换一张
取 消