请看下面的代码,我想在这里得到$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']
答案 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;