Php 使用平面数组获取多维数组值
我有以下数组:Php 使用平面数组获取多维数组值,php,arrays,Php,Arrays,我有以下数组: $people['men'] = [ 'first_name' => 'John', 'last_name' => 'Doe' ]; 我有以下平面阵列: $name = ['men', 'first_name']; 现在我想创建一个函数,该函数“读取”平面数组,并根据平面数组元素的顺序从多维数组中获取值 function read($multidimensionalArray,$flatArray){ // do stuff here }
$people['men'] = [
'first_name' => 'John',
'last_name' => 'Doe'
];
我有以下平面阵列:
$name = ['men', 'first_name'];
现在我想创建一个函数,该函数“读取”平面数组,并根据平面数组元素的顺序从多维数组中获取值
function read($multidimensionalArray,$flatArray){
// do stuff here
}
echo read($people,$name); // must print 'John'
这有可能实现吗?那要走哪条路呢?我真的被这件事弄得头晕目眩。我根本不知道如何开始
提前感谢。这应该归功于技巧:
<?php
$people['men'] = [
'first_name' => 'John',
'last_name' => 'Doe'
];
$name = ['men', 'first_name'];
echo read($people,$name);
function read($multidimensionalArray,$flatArray){
$cur = $multidimensionalArray;
foreach($flatArray as $key)
{
$cur = $cur[$key];
}
return $cur;
}
看起来您只需要:
echo $multidimensionalArray[$flatArray[0]][$flatArray[1]];
您可以使用递归函数来实现这一点
function read(&$array, $path) {
// return null if one of the keys in the path is not present
if (!isset($array[$key = array_shift($path)])) return null;
// call recursively until you reach the end of the path, then return the value
return $path ? read($array[$key], $path) : $array[$key];
}
echo read($people, $name);
您也可以使用array\u reduce
$val = array_reduce($name, function($carry, $item) {
return $carry[$item];
}, $people);
看看这是否有帮助: