douxieqiu0651 2013-02-19 15:50
浏览 193
已采纳

将一维数组转换为多维数组

suppose i have this array:

Array
(
  [0] => Array
  (
    [name] => ELECTRONICS
    [depth] => 0
  )

  [1] => Array
  (
    [name] => TELEVISIONS
    [depth] => 1
  )

  [2] => Array
  (
    [name] => TUBE
    [depth] => 2
  )

  [3] => Array
  (
    [name] => LCD
    [depth] => 2
  )

  [4] => Array
  (
    [name] => PLASMA
    [depth] => 2
  )

  [5] => Array
  (
    [name] => PORTABLE ELECTRONICS
    [depth] => 1
  )
)

i want it to be converted into a multi-dimensional array such that immediate elements with a depth higher than the previous element will go inside the previous element with the key "children". like this:

Array
(
  [0] => Array
  (
    [name] => ELECTRONICS
    [depth] => 0
    [children] => Array
    (
      [0] => Array
      (
        [name] => TELEVISIONS
        [depth] => 1
        [children] => Array
        (
          [0] => Array
          (
            [name] => TUBE
            [depth] => 2
          )

          [1] => Array
          (
            [name] => LCD
            [depth] => 2
          )

          [2] => Array
          (
            [name] => PLASMA
            [depth] => 2
          )
        )
      )

      [1] => Array
      (
        [name] => PORTABLE ELECTRONICS
        [depth] => 1
      )
    )
  )
)

would greatly appreciate your help. thanks ;)

  • 写回答

3条回答 默认 最新

  • duanlian1320 2013-02-19 17:05
    关注

    Here's my crack at it... Uses a foreach loop and an array of pointers to keep track of a bunch of different parent pointers.

    $multi_dimensional = array();
    $last_depth = 0;
    $parent = &$multi_dimensional;
    $parents[$last_depth] = &$parent;
    
    
    foreach ($start as $idx => $data) {
      // same/increasing depth
      if ($last_depth <= $data['depth']) {
        $parent['children'][] = $data;  
      } 
    
      // increasing depth
      if ($last_depth < $data['depth']) {
        $parents[$last_depth] = &$parent;
      }
    
      // decreasing depth
      if ($last_depth > $data['depth']) {
        $parent = &$parents[$data['depth']-1];
        $parent['children'][] = $data;  
      }
    
      // look ahead and prepare parent in increasing
      if (isset($start[$idx+1]) && $start[$idx+1]['depth'] > $data['depth']) {
        $last_insert_idx = count($parent['children'])-1;
        $parent = &$parent['children'][$last_insert_idx];
      }
      $last_depth = $data['depth'];
    }
    
    // initial values are in child "children" array
    $result = $multi_dimensional['children'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记