5

If an array $array

and keys sequence $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.?

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


Updated, so the final code according to 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;
    }
}
4

1 回答 1

3

用一个简单的循环:

//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]];
}

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

于 2013-09-19T10:35:02.897 回答