如何使用带有组合键的字符串从多维数组中获取值?

时间:2013-11-28 03:31:45

标签: php arrays

请看下面的代码,我想在这里得到$arr['jimmy']['age']。字符串为jimmy.age,将从ajax

发布
<?php
$arr=array(
    'jimmy'=>array(
        'age'=>31
    )
);

$str='jimmy.age';
$keys_tree=explode('.',$str);
$x='';
foreach($keys_tree as $k=>$v){
    $x.='["'.$v.'"]';
}
echo $arr$x; //error here; how can i get $arr['jimmy']['age'] using $arr joining str ['jimmy']['age']

1 个答案:

答案 0 :(得分:2)

一种方法是遍历数组并使用引用跟踪每个级别:

$str ='jimmy.age';
$keys_tree = explode('.', $str);

$pointer = $arr;

while($key = array_shift($keys_tree)){

  if(!isset($pointer[$key]))
    throw new Exception(sprintf("Key %s doesn't exist", $key));

  $pointer = &$pointer[$key];      
}

echo $pointer;