我有以下数组:
array('data' => array('one' => 'first', 'two' => 'second'));
如何使用字符串获取键'one'的值:
echo __('data.one');
function __($key) {
$parts = explode('.', $key);
$array = array('data' => array('one' => 'first', 'two' => 'second'));
return ???;
}
谢谢你!
答案 0 :(得分:2)
添加您自己的错误处理,以防关键路径不在您的数组中,但类似于:
$array = array('data' => array('one' => 'first', 'two' => 'second'));
$key = 'data.one';
function find($key, $array) {
$parts = explode('.', $key);
foreach ($parts as $part) {
$array = $array[$part];
}
return $array;
}
$result = find($key, $array);
var_dump($result);
答案 1 :(得分:0)
这应该适合你:
return $array["data"]["one"];
另外,有关更多信息和了解一点,请参阅:http://php.net/manual/en/language.types.array.php
并且:PHP - Accessing Multidimensional Array Values
修改强>
这应该适合你:
<?php
$str = "data.one";
$keys = explode(".", $str);
$array = array('data' => array('one' => 'first', 'two' => 'second'));
$access = $array;
foreach($keys as $v)
$access = $access[$v];
echo $access;
?>