当运行此代码:

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天,这样,如果你能帮助我,请张贴在这里...

有帮助吗?

解决方案

尝试该算法:

$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

其他提示

试试这个代码,而不是:

<?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>

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top