0

我有一系列看起来像的类别

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

我正在尝试构建的是一个层次数组(path键显示基于的关系id),因此输出顺序正确(首先是根父级,然后是子级,然后是更多子级)并name根据向下的距离缩进孩子是。最终结果应类似于:

A
-B
--C
--D

这是我到目前为止所拥有的,但它显然不起作用

$categoryTree = array();

foreach ($categories as $category) {

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

ksort($categoryTree);

var_export($categoryTree);

结果是:

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

我怎样才能以正确的顺序得到这些?(如果可以订购兄弟姐妹,id那也太花哨了)

4

2 回答 2

1

这是基于 One Trick Pony 的回答,但正确处理了多于一位的 ID。

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], "\n";
}
于 2013-05-01T17:49:46.840 回答
1

计算斜线的数量以生成值前缀,然后按路径(键)排序?

foreach ($categories as $category)
  $output[$category['path']] =
    str_repeat('-', substr_count($category['path'], '/')) . $category['name'];

ksort($output, SORT_STRING);
于 2013-05-01T16:54:29.360 回答