How do I access values in a multidimensional array dynamically with a variable number of indices?
从本质上讲,我有一个这样的多维数组(实际上更广泛,但这是我需要访问的裸露的骨架):
1 2 3 4 5 6 7 8 9 10 11 12 | $arr = [ 1 => [ 'val1' => 'foo', 'val2' => 'bar', ], 2 => [ 'type1' => [ 'val3' => 'baz', 'val4' => 'fuz', ], ], ] |
我将动态访问该数组,直到尝试访问$ arr [1]或$ arr [2]时,我才知道。因此,在那个时候到来之前,我还不知道需要深入多少层。我一直在寻找可以访问多维数组深处不同数量级别的函数,但找不到类似的东西。我知道我可以使用if或switch语句来做到这一点,但是我正在尝试将其简化为:
1 2 3 |
我的问题是我无法弄清楚如何构建一个字符串来用适当数量的索引替换" ......"。我尝试使用循环制作字符串:
1 2 3 4 5 6 7 | function getAccessString( array $arrOfIndices ) { $str = ''; foreach( $arrOfIndices as $index ) { $str .= '['.$index.']'; } return $str; } |
但是,我无法以某种方式访问??该字符串生成函数,因为我可以以访问多维数组的方式对其进行连接。
P.S。如果没有办法按照这种方式以非常简单的格式访问此数组...
1 2 3 |
...我将仅使用switch语句。使用迭代器,解析数组和其他东西不会比我已经拥有的switch语句更简单。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | function getArrayElement($arr, $arrayOfIndices) { $result = $arr; foreach ($arrayOfIndices as $index) { $result = $result[$index]; } return $result; } $arr = [ 1 => [ 'val1' => 'foo', 'val2' => 'bar', ], 2 => [ 'type1' => [ 'val3' => 'baz', 'val4' => 'fuz', ], ], ]; echo getArrayElement($arr, [1, 'val1']); // echoes foo echo getArrayElement($arr, [2, 'type1', 'val4']); // echoes fuz |
您可能要考虑使用PHP的递归迭代器展平数组-
1 2 3 4 5 6 7 8 9 10 | function findValue($needle, $haystack) { $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack)); foreach($iterator as $key=>$value){ if($key == $needle) { return $value; } } } $result = findValue('val3', $arr); echo $result; // returns 'baz' |
此设置假定您的阵列中没有重复的键。