doupingmao1903 2013-07-26 18:49
浏览 29

从另一个数组中的键获取多维数组值

I've got an array containing values I wish to use as keys, such as:

$keys = array("first", "second", "third", "fourth");

The count and contents of these values will be changing dynamically within a loop. I want them to become the keys of a multidimensional array, but the count of the keys array will always be changing, so while this would work for that first array of keys:

$multidimensional[$keys[0]][$keys[1]][$keys[2]][$keys[3]] = "some value";

Later in the loop the keys may be something like:

$keys = array("first", "second", "gamma", "delta", "theta", "kappa");

So using this in the loop:

$multidimensional[$keys[0]][$keys[1]][$keys[2]][$keys[3]] = "some value";

Will not work, and needs to be dynamic too based on the count of the keys.

I've gone through each of the array functions in the PHP manual and can't seem to find something that fulfills this purpose. Am I totally overlooking something basic here? Maybe some curly brace magic?

  • 写回答

1条回答 默认 最新

  • doupiai5597 2013-07-26 18:59
    关注

    There you go...

    function setMultidimensionalValue($value, array $keys, array $multidimensional)
    {
      $node = &$multidimensional;
      foreach ($keys as $key)
      {
        if (!isset($node[$key]))
          $node[$key] = null;
        $node = &$node[$key];
      }
      $node = $value;
      return $multidimensional;
    }
    
    // Example of usage
    $multidimensional = array();
    var_dump(setMultidimensionalValue('value', array('first', 'second', 'third'), $multidimensional));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 qgcomp混合物线性模型分析的代码出现错误:Model aliasing occurred
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答