如何使用分层数据结构打印列表?

时间:2009-05-23 13:58:14

标签: php list hierarchy

当我运行此代码时:

foreach ($tree as $node) {
    echo str_repeat(' ', $node->tree_depth * 4) . $node->id . PHP_EOL;
}

我得到格式良好的文字,如:

Food
 Fruit
   Red
     Cherry
     Strawberry
               Cool
               Not cool
   Yellow
     Banana
 Meat
   Beef
   Pork

但我想创建一个包含<ul><li>...的列表:

我尝试过:

echo '<ul>';
$prev_depth = 0;
foreach($table->fetchTree() as $row) {
    if ($row->tree_depth > $prev_depth) {
        echo '<li><ul>';
    } else if ($row->tree_depth < $prev_depth) {
        echo '</li></ul>';
    }
    echo '<li>' . $row->name . '</li>';
    $prev_depth = $row->tree_depth;
}
echo '</ul>';

但我有一些额外的ul标签等等。我失去了2天,如果你能帮助我,请在这里发帖...

2 个答案:

答案 0 :(得分:6)

试试这个算法:

$tree = array(
    array('Food', 0),
    array('Fruit', 1),
    array('Red', 2),
    array('Cherry', 3),
    array('Strawberry', 3),
    array('Cool', 4),
    array('Not cool', 4),
    array('Yellow', 2),
    array('Banana', 3),
    array('Meat', 0),
    array('Beef', 1),
    array('Pork', 1),
);

$depth = -1;
$flag = false;
foreach ($tree as $row) {
    while ($row[1] > $depth) {
        echo "<ul>\n", "<li>";
        $flag = false;
        $depth++;
    }
    while ($row[1] < $depth) {
        echo "</li>\n", "</ul>\n";
        $depth--;
    }
    if ($flag) {
        echo "</li>\n", "<li>";
        $flag = false;
    }
    echo $row[0];
    $flag = true;
}
while ($depth-- > -1) {
    echo "</li>\n", "</ul>\n";
}

在这里,您只需要$tree替换$table->fetchTree()$row[0]替换$row->name$row[1]替换$row->tree_depth

答案 1 :(得分:0)

请尝试使用此代码:

<?php
echo "<ul>\n";

$tree = array(
    array('Food', 0),
    array('Fruit', 1),
    array('Red', 5),
    array('Cherry', 3),
    array('Strawberry', 3),
    array('Cool', 4),
    array('Not cool', 4),
    array('Yellow', 2),
    array('Banana', 3),
    array('Meat', 0),
    array('Beef', 4),
    array('Pork', 2),
);

$depth = 0;

foreach ($tree as $node) {
  if ($node[1] > $depth)
    echo str_repeat("<ul>\n", $node[1] - $depth);
  if ($node[1] < $depth)
    echo str_repeat("</ul>\n", $depth - $node[1]);
  $depth = $node[1];

  echo "<li>" .  $node[0] . "\n";
}
echo str_repeat("</ul>\n", $depth+1);
?>

我已将其更新为输出较少的<li>标记,从而减少了项目符号的数量。但另一方面,这将生成不会验证的HTML,因为跳转多个级别将导致生成<ul><ul>