PHP使用函数参数“获取多维数组中某个级别的值”;路径“;
我有一个N级的多维数组,如下所示:PHP使用函数参数“获取多维数组中某个级别的值”;路径“;,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我有一个N级的多维数组,如下所示: $a = array( 'a'=>1, 'b'=>array( 'x'=>array( 'p'=>array( 't'=>2 ) ) ), 'c'=>3 ); 如何使用函数中的参数数组通过“path”获取值 function get(){ $args = func_get_args(); $b = (global) $a; // ??
$a = array(
'a'=>1,
'b'=>array(
'x'=>array(
'p'=>array(
't'=>2
)
)
),
'c'=>3
);
如何使用函数中的参数数组通过“path”获取值
function get(){
$args = func_get_args();
$b = (global) $a;
// ????
}
$v = get('b','x','p'); // expected: Array ( [t] => 2 )
逐个遍历参数数组中的一个元素:
function get() {
global $a;
$args = func_get_args();
$currentElement = $a;
foreach ($args as $index) {
$currentElement = $currentElement[$index];
}
return $currentElement;
}
更详细的php实现方法:
function array_get_path(array $array, $path) {
$current = $array;
if(!empty($path)) {
foreach($path as $elem) {
if(isset($current[$elem])) {
$current = &$current[$elem];
} else {
return $current;
}
}
}
return $current;
}
出于好奇,“多一点php方式”是什么意思?命名并使用数组作为参数,就像在stdlib中一样
function array_get_path(array $array, $path) {
$current = $array;
if(!empty($path)) {
foreach($path as $elem) {
if(isset($current[$elem])) {
$current = &$current[$elem];
} else {
return $current;
}
}
}
return $current;
}