How to print list using hierarchical data structure?

匿名 (未验证) 提交于 2019-12-03 02:54:01

问题:

When I run this code:

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

I get well formatted text like:

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

But I want to create a list with <ul><li>...:

I tried with:

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

But I have some extra ul tags and so on. I lost 2 days on this so if you can help me please post here...

回答1:

Try this algorithm:

$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"; } 

Here you just need to replace $tree by $table->fetchTree(), $row[0] by $row->name and $row[1] by $row->tree_depth.



回答2:

Try this code instead:

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

I've updated it to output fewer <li> tags, thereby reducing the number of bullets. But on the other hand, this will generate HTML that wont validate since a jump of more than one level will result in a <ul><ul> being generated.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!