【问题标题】:Access deep array value in php using an array of keys/indices in php?使用php中的键/索引数组访问php中的深层数组值?
【发布时间】:2015-01-31 18:15:50
【问题描述】:

假设你有这个数组:

$object = array ('a' => array ( 'b' => array('c' = 'value'), 'd' => 3));
$indices = array ('a', 'b', 'c');

有没有一种简单的方法可以访问 $object['a']['b']['c'](来自 $indices 数组的键)?

这是我尝试过的:

function accessObjectKey ($object, $levels) {
    if (is_string($levels)) 
        $levels = explode ('.', $levels);
    //
    for ($i=0; $i<count($levels); $i++) {
        if ($i == count($levels) && key_exists($levels[$i], $object)) {
            $value = $object[$levels[$i]];
        }
        else {
            $value = accessObjectKey ($object, array_shift($levels));
        }
    }
    return $value;
}

谢谢

【问题讨论】:

  • 你在函数的 $levels 参数中发送什么?
  • 首先想到的是递归函数。

标签: php arrays


【解决方案1】:

首先(你有错字array('c' = 'value'),应该是array('c' =&gt; 'value'),) 我尝试使用您的代码:

$object = array ('a' => array ( 'b' => array('c' => 'value'), 'd' => 3));
$indices = array ('a', 'b', 'c');

echo accessObjectKey($object,$indices);

这给我返回了一个错误:

致命错误:达到“100”的最大函数嵌套级别, 中止!

我对你的函数代码有点困惑,很抱歉我创建了我的 它并不完美,但按预期返回value

function getByPath($arr,$path) {
     if (!isset($arr[$path[0]])) {
        return 'There is no '.$path[0].' element!';
     } elseif(count($path)==1) {
        return $arr[$path[0]];
     } elseif(!is_array($arr[$path[0]])) {
        return 'Element '.$path[0].' is not array! ';
     } else {
    $key = array_shift($path);     
        return getByPath($arr[$key],$path);
     }
}

$object = array ('a' => array ( 'b' => array('c' => 'value'), 'd' => 3));
$indices = array ('a', 'b', 'c');

echo getByPath($object,$indices);

输出:

value

【讨论】:

    【解决方案2】:

    这是另一个选项,来自https://baohx2000.medium.com/reaching-deep-into-arrays-using-array-reduce-in-php-9ff9e39a9ca8

    function getArrayPath(array $path, array $deepArray) {
       $reduce = function(array $xs, $x) {
          return (
            array_key_exists($x, $xs)
          ) ? $xs[$x] : null;
       };
       return array_reduce($path, $reduce, $deepArray);
    }
    
    $x = [
      'a' => 1,
      'b' => [
        'c' => 2,
        'd' => [3, 4, 5],
      ],
    ];
    
    print_r(getArrayPath(['b','d', 0], $x));  // 3
    

    【讨论】:

      【解决方案3】:

      另一种技巧是使用explicit stacking

      我在搜索this CodeReview question 的相关技术时发现了这个页面。

      通过“堆叠”,我实际上是指迭代键数组,这些键指示所需数组值的路径,每次找到键时,用新遇到的子数组覆盖父数组。

      代码:(Demo)

      function getFromKeyPath(array $array, array $keys) {
          foreach ($keys as $index => $key) {
              if (!key_exists($key, $array)) {
                  throw new Exception("key $key not found at level index $index");
              }
              $array = $array[$key];
          }
          return $array;
      }
      
      $array = ['a' => ['b' => ['c' => 'value'], 'd' => 3]];
      $keys = ['a', 'b', 'c'];
      
      try {
          var_export(getFromKeyPath($array, $keys));
      } catch (Exception $e) {
          echo $e->getMessage();
      }
      // 'value'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-14
        • 1970-01-01
        • 2012-08-29
        • 1970-01-01
        • 2022-01-06
        • 1970-01-01
        • 2013-09-08
        • 2015-09-19
        相关资源
        最近更新 更多