How to print list using hierarchical data structure?

后端 未结 2 1934
攒了一身酷
攒了一身酷 2021-02-11 06:41

When I run this code:

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

I get well fo

2条回答
  •  别那么骄傲
    2021-02-11 07:20

    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 "
      \n", "
    • "; $flag = false; $depth++; } while ($row[1] < $depth) { echo "
    • \n", "
    \n"; $depth--; } if ($flag) { echo "
  • \n", "
  • "; $flag = false; } echo $row[0]; $flag = true; } while ($depth-- > -1) { echo "
  • \n", "
\n"; }

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

提交回复
热议问题