PHP使用函数参数作为“路径”获取多维数组中的级别值

时间:2014-09-04 17:35:00

标签: php arrays multidimensional-array

我有一个多维数组,其中包含N个级别:

$a = array(
'a'=>1,
'b'=>array(
    'x'=>array(
        'p'=>array(
            't'=>2
        )
    )
),
'c'=>3
);

如何通过"路径"获取价值?在函数中使用参数数组?

function get(){
   $args = func_get_args();
   $b = (global) $a;
   // ????
}
$v = get('b','x','p'); // expected: Array ( [t] => 2 )

3 个答案:

答案 0 :(得分:1)

function get() {
    global $a;
    $current = $a;
    $args = func_get_args();
    foreach($args as $key) {
        $current = $current[$key];
    }
    return $current;
}

答案 1 :(得分:1)

更多的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;
}

答案 2 :(得分:0)

一次向下移动一个元素的参数数组:

function get() {   
    global $a;
    $args = func_get_args();
    $currentElement = $a;

    foreach ($args as $index) {
        $currentElement = $currentElement[$index];
    }

    return $currentElement;
}