Question

Quand je lance ce code:

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

Je me bien formaté comme texte:

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

Mais je veux créer une liste avec <ul><li>...:

J'ai essayé avec:

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

Mais j'ai quelques balises supplémentaires ul et ainsi de suite. J'ai perdu 2 jours, donc si vous pouvez me aider s'il vous plaît poster ici ...

Était-ce utile?

La solution

Essayez cet algorithme:

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

Ici, vous avez juste besoin de remplacer $tree par $table->fetchTree(), $row[0] par $row->name et $row[1] par $row->tree_depth.

Autres conseils

Essayez ce code à la place:

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

Je l'ai mis à jour à la production moins balises <li>, réduisant ainsi le nombre de balles. Mais d'autre part, cela va générer HTML qui valident l'habitude depuis un bond de plus d'un niveau se traduira par une <ul><ul> générée.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top