通过一系列键在多维数组中深入获取值

时间:2021-12-10 21:35:56

If an array $array

如果是一个数组$ array

and keys sequence $keys = array('key1','key2','key3')

和键序列$ keys = array('key1','key2','key3')

how to get $array[$keys[1]][$keys[2]][$keys[3]] given the number of keys is unsure, there could be 4 keys, or 1 key, etc.?

如果获得$ array [$ keys [1]] [$ keys [2]] [$ keys [3]],如果键的数量不确定,可能有4个键,或1个键等等?

My code currently is:

我的代码目前是:

switch(count($keys)) {
    case 1:
        if(array_isset($array[$keys[0]]), $array)
            $value = $array[$keys[0]];
        break;
    case 2:
        if(array_isset($array[$keys[0]][$keys[1]]), $array[$keys[0]])
            $value = $array[$keys[0]][$keys[1]];
        break;
    case 3:
        if(array_isset($array[$keys[0]][$keys[1]][$keys[2]]), $array[$keys[0]][$keys[1]])
            $value = $array[$keys[0]][$keys[1]][$keys[2]];
        break;
    case 4:
        if(array_isset($array[$keys[0]][$keys[1]][$keys[2]][$keys[3]]), $array[$keys[0]][$keys[1]][$keys[2]])
            $value = $array[$keys[0]][$keys[1]][$keys[2]][$keys[3]];
        break;
    default:
        break;
}

function array_isset($key, Array $array) {
  if(isset($array[$key])) {
    return true;
  }
  return array_key_exists($key, $array);
}

Any better idea? I don't want to use eval

有什么好主意吗?我不想使用eval


Updated, so the final code according to Alma Do Mundo

更新了,所以根据Alma Do Mundo的最终代码

$result = $array[$keys[0]];
for($i=1;$i<count($keys);$i++) {
    if(array_isset($keys[$i], $result))
        $result = $result[$keys[$i]];
    else {
        $result = null;
        break;
    }
}

1 个解决方案

#1


3  

With a simple loop:

通过简单的循环:

//for PHP <=5.3 replace short [] to array()
$rgData   = ['key1'=>['key2'=>['key3'=>'test', 'key4'=>'data'], 'key5'=>'done']];
$rgKeys   = ['key1','key2','key3'];
$rgResult = $rgData[$rgKeys[0]];
for($i=1; $i<count($rgKeys); $i++)
{
   $rgResult=$rgResult[$rgKeys[$i]];
}

There could be an option with eval, but I'd say - never use eval - if you can avoid it.

eval可能有一个选项,但我会说 - 永远不要使用eval - 如果你可以避免它。

#1


3  

With a simple loop:

通过简单的循环:

//for PHP <=5.3 replace short [] to array()
$rgData   = ['key1'=>['key2'=>['key3'=>'test', 'key4'=>'data'], 'key5'=>'done']];
$rgKeys   = ['key1','key2','key3'];
$rgResult = $rgData[$rgKeys[0]];
for($i=1; $i<count($rgKeys); $i++)
{
   $rgResult=$rgResult[$rgKeys[$i]];
}

There could be an option with eval, but I'd say - never use eval - if you can avoid it.

eval可能有一个选项,但我会说 - 永远不要使用eval - 如果你可以避免它。