使用另一个数组搜索多维数组的键 [英] Searching multi-dimensional array's keys using a another array
问题描述
是否存在一种优雅的方法来从大型多维数组中获取值,并使用另一个数组作为查找键?
Is there an elegant way of getting values from a massive multi-dimensional array using another array for the keys to lookup?
例如
$cats[A][A1][A11][A111] = $val;
$cats[A][A1][A11][A112] = $val;
$cats[A][A1][A12] = $val;
$cats[A][A1][A12][A121] = $val;
$cats[A][A2] = $val;
$cats[A][A2][A21] = $val;
$cats[A][A2][A22] = $val;
$cats[A][A2][A22][A221] = $val;
$cats[A][A2][A22][A222] = $val;
使用 $ keys = Array('A','A2','A22','A221')从
$ cats
访问值;
access values from $cats
using $keys = Array ('A', 'A2', 'A22', 'A221');
无需检查 $ keys
的长度并执行类似的操作...
without checking the length of $keys
and doing something like...
switch (count($keys)) {
case 1: $val = $cats[$keys[0]]; break;
case 2: $val = $cats[$key[0]][$key[1]]; break;
case 3: $val = $cats[$key[0]][$key[1]][$key[2]]; break;
...
}
非常感谢.
推荐答案
为什么不使用递归?像这样:
Why not use recursion? Something like this:
function get_val($array, $keys) {
if(empty($keys) || !is_array($keys) || !is_array($array)) return $array;
else {
$first_key = array_shift($keys);
return get_val($array[$first_key], $keys);
}
}
我本来是将其写成循环的,但是出于某种原因将其更改为递归.确实,正如yeoman所说,递归函数比循环更可能导致堆栈溢出,尤其是在您的数组足够大(PHP确实支持结束递归)的情况下,因此,此循环应达到相同的目的:
I originally had this written in a loop, but changed it to recursive for some reason. It's true, as yeoman said, that a recursive function is more likely than a loop to cause a stack overflow, especially if your array is sufficiently large (PHP does support end recursion), so here's a loop that should accomplish the same purpose:
// given a multidimensional array $array and single-dimensional array of keys $keys
$desired_value = $array;
while(count($keys) > 0) {
$first_key = array_shift($keys);
$desired_value = $desired_value[$first_key];
}
这篇关于使用另一个数组搜索多维数组的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!