dongshang1979 2013-10-11 15:22
浏览 31
已采纳

将扁平结构整理成树只知道父母

Given the following structure of arrays:

array(
   55 => array(
       'ident' => 'test 1',
       'depth' => 1,
   ),
   77 => array(
       'parent_id' => 55,
       'ident' => 'test 2',
       'depth' => 2,
   )
);

Is there a general algorithm that can be used to turn that into a nested tree?

i.e.

array(
   55 => array(
       'ident' => 'test 1',
       'depth' => 1,
       'children' => array(
            77 => array(
                'parent_id' => 55,
                'ident' => 'test 2',
                'depth' => 2,
           )
       )
   )
);

The example i have provided is simplified, the real case includes hundreds of nodes + a depth of up to 15.

  • 写回答

1条回答 默认 最新

  • dongzhiqi0332 2013-10-11 15:26
    关注

    Working with references helps a lot. This way you can still append to the children even if they're already inserted.

    foreach ($array as $key => &$sub) {
        if (isset($sub['parent_id'])) {
            $array[$sub['parent_id']]['children'][$key] = &$sub;
        }
    }
    unset($sub); // unset the reference to make sure to not overwrite it later...
    
    // now remove the entries with parents
    foreach ($array as $key => $sub) {
        if (isset($sub['parent_id'])) { 
            unset($array[$key]);
        }
    }
    

    Some demo for this: http://3v4l.org/D6l6U#v500

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的
  • ¥15 我看了您的文章,遇到了个问题。
  • ¥15 GitHubssh虚拟机连接不上