dqk42179 2013-05-01 16:45
浏览 54
已采纳

从数组构建分层列表

I have an array of categories that looks something like

array(
  array(
    'id' => '1',
    'path' => '1',
    'children_count' => '16',
    'name' => 'A'
  ),
  array(
    'id' => '3',
    'path' => '1/2/3',
    'children_count' => '0',
    'name' => 'C'
  ),
  array(
    'id' => '2',
    'path' => '1/2',
    'children_count' => '9',
    'name' => 'B'
  ),
  array(
    'id' => '4',
    'path' => '1/2/4',
    'children_count' => '0',
    'name' => 'D'
  )
)

What I'm trying to build is a hierarchal array (the path key shows the relation based on id), so the output is in the correct order (root parent first, then children, then more children) and indent the name based on how far down in the child is. The end result should look something like:

A
-B
--C
--D

Here's what I have so far, but it's obviously not working

$categoryTree = array();

foreach ($categories as $category) {

    $categoryTree[(string)$category['path']] = str_repeat("-", substr_count($category['path'], "/")) . $category['name'];
}

ksort($categoryTree);

var_export($categoryTree);

Which comes out to:

array (
  '1/2' => '-B',
  '1/2/3' => '--C',
  '1/2/4' => '--D',
  1 => 'A'
)

How can I get these in the correct order? (and if siblings could be ordered by id that would be dandy too)

  • 写回答

2条回答 默认 最新

  • duanchoupo1104 2013-05-01 17:49
    关注

    This is based on One Trick Pony's answer, but correctly handles IDs with more than one digit.

    foreach ($categories as $category)
      $output[$category['path']] =
        str_repeat('-', substr_count($category['path'], '/')) . $category['name'];
    
    $paths = array_keys($output);
    natsort($paths);
    
    foreach ($paths as $path) {
      echo $output[$path], "
    ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算