假设您有以下数组:
$object = array ('a' => array ( 'b' => array('c' = 'value'), 'd' => 3));
$indices = array ('a', 'b', 'c');
是否有一种简单的方法来访问$ object ['a'] ['b'] ['c'](来自$ indices数组的键)?
这是我尝试的:
function accessObjectKey ($object, $levels) {
if (is_string($levels))
$levels = explode ('.', $levels);
//
for ($i=0; $i<count($levels); $i++) {
if ($i == count($levels) && key_exists($levels[$i], $object)) {
$value = $object[$levels[$i]];
}
else {
$value = accessObjectKey ($object, array_shift($levels));
}
}
return $value;
}
谢谢
首先(你有错字array('c' = 'value'),
应该是array('c' => 'value'),
)我试图用你的代码:
$object = array ('a' => array ( 'b' => array('c' => 'value'), 'd' => 3));
$indices = array ('a', 'b', 'c');
echo accessObjectKey($object,$indices);
那给我一个错误:
致命错误:达到最大功能嵌套级别'100',正在中止!
我对您的功能代码有点困惑,所以很抱歉,我创建了我的代码,它不是完美的,但value
按预期返回:
function getByPath($arr,$path) {
if (!isset($arr[$path[0]])) {
return 'There is no '.$path[0].' element!';
} elseif(count($path)==1) {
return $arr[$path[0]];
} elseif(!is_array($arr[$path[0]])) {
return 'Element '.$path[0].' is not array! ';
} else {
$key = array_shift($path);
return getByPath($arr[$key],$path);
}
}
$object = array ('a' => array ( 'b' => array('c' => 'value'), 'd' => 3));
$indices = array ('a', 'b', 'c');
echo getByPath($object,$indices);
输出:
value
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句