假设你有这个数组:
$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;
}
谢谢
答案 0 :(得分:1)
首先(你有错字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
答案 1 :(得分:0)
这是另一个选项,来自 https://baohx2000.medium.com/reaching-deep-into-arrays-using-array-reduce-in-php-9ff9e39a9ca8
function getArrayPath(array $path, array $deepArray) {
$reduce = function(array $xs, $x) {
return (
array_key_exists($x, $xs)
) ? $xs[$x] : null;
};
return array_reduce($path, $reduce, $deepArray);
}
$x = [
'a' => 1,
'b' => [
'c' => 2,
'd' => [3, 4, 5],
],
];
print_r(getArrayPath(['b','d', 0], $x)); // 3