在一个多维数组访问一个任意深度的关键 [英] Accessing an arbitrarily deep key in a multi-dimensional array
本文介绍了在一个多维数组访问一个任意深度的关键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个包含一个数组 ['键1','密钥2,KEY3']
有什么办法到此映射到一个数组 $数组['key1的'] ['密钥2'] ['KEY3']
不使用循环或eval()函数?
的阵列的实施例
$ VAR = [
'键1'=> [
subkey1'=> [
finalkey'=> '值',
]
'子'=> [
otherkey'=> '值',
]
]
'键2'=> 嗒嗒
];
然后,我有一个这样的数组:
$键= ['键1','subkey1','finalkey']
或
$键= ['键1','子']
解决方案
函数array_find($针,&安培; $草垛)
{
$电流= array_shift($针);
如果(!使用isset($大海捞针[$当前]))
{
返回null;
}
如果(!is_array($大海捞针[$当前]))
{
返回$草垛[$当前];
}
返回array_find($针,干草堆$ [$当前]);
}
If I have an array that contains ['key1', 'key2', 'key3']
is there any way to map this to an array $array['key1']['key2']['key3']
without using loops or eval()?
Example of an array:
$var = [
'key1' => [
'subkey1' => [
'finalkey' => 'value',
],
'subkey' => [
'otherkey' => 'value',
],
],
'key2' => 'blah'
];
And then I have an array like this:
$keys = ['key1', 'subkey1', 'finalkey']
or
$keys = ['key1', 'subkey']
解决方案
function array_find($needle, &$haystack)
{
$current = array_shift($needle);
if(!isset($haystack[$current]))
{
return null;
}
if(!is_array($haystack[$current]))
{
return $haystack[$current];
}
return array_find($needle, $haystack[$current]);
}
这篇关于在一个多维数组访问一个任意深度的关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文