Como lista de imprimir usando a estrutura hierárquica de dados?
Pergunta
Quando eu executar esse código:
foreach ($tree as $node) {
echo str_repeat(' ', $node->tree_depth * 4) . $node->id . PHP_EOL;
}
texto eu fico bem formatado como:
Food
Fruit
Red
Cherry
Strawberry
Cool
Not cool
Yellow
Banana
Meat
Beef
Pork
Mas eu quero criar uma lista com <ul><li>...
:
Eu tentei com:
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>';
Mas eu tenho algumas tags ul extras e assim por diante. Eu perdi 2 dias neste isso, se você pode me ajudar por favor postar aqui ...
Solução
Tente este algoritmo:
$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";
}
Aqui você só precisa substituir $tree
por $table->fetchTree()
, $row[0]
por $row->name
e $row[1]
por $row->tree_depth
.
Outras dicas
Tente este código em vez disso:
<?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);
?>
Eu atualizei para a saída menos tags <li>
, reduzindo assim o número de balas. Mas, por outro lado, isso irá gerar HTML que não vai validar desde um salto de mais de um nível irá resultar em uma <ul><ul>
sendo gerado.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow