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条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大