PHP-从键数组中获取嵌套数组的值 [英] PHP - Getting Value of Nested Array from Array of Keys
本文介绍了PHP-从键数组中获取嵌套数组的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下内容:
$values = Array (
['level1'] => Array (
['level2'] => Array(
['level3'] => 'Value'
)
)
)
我还有一个键数组:
$keys = Array (
[0] => 'level1',
[1] => 'level2',
[2] => 'level3'
)
我希望能够使用$ keys数组,因此我可以提出:$ values ['level1'] ['level2'] ['level3'].级别和键名称的数量将发生变化,因此我需要一个解决方案,该解决方案将读取$ keys数组,然后遍历$ values直到获得最终值.
I want to be able to use the $keys array so I can come up with: $values['level1']['level2']['level3']. The number of levels and key names will change so I need a solution that will read my $keys array and then loop through $values until I get the end value.
推荐答案
您可以遍历$values
并像这样存储$ref
:
You could iterate over $values
and store a $ref
like this :
$ref = $values ;
foreach ($keys as $key) {
if (isset($ref[$key])) {
$ref = $ref[$key];
}
}
echo $ref ; // Value
您还可以使用引用(&
)避免复制数组:
You also could use references (&
) to avoid copy of arrays :
$ref = &$values ;
foreach ($keys as &$key) {
if (isset($ref[$key])) {
$ref = &$ref[$key];
}
}
echo $ref ;
这篇关于PHP-从键数组中获取嵌套数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文