계층 적 데이터 구조를 사용하여 목록을 인쇄하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/901576

  •  05-09-2019
  •  | 
  •  

문제

이 코드를 실행할 때 :

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