How do I create a nested list inside of a while loop?

前端 未结 3 638
孤街浪徒
孤街浪徒 2021-01-21 20:29

I\'m having trouble trying to get a nested < ul > inside of a while loop. I\'m not sure if this even possible so i\'m open to alternatives.

Here\'s a quick image of w

相关标签:
3条回答
  • 2021-01-21 20:51
    $result = $conn->query($sql) or die(mysqli_error());
    
    $last_category = 0;
    
    while ($row = $result->fetch_assoc()) {
    
        if($row['drinks_category_id'] != $last_category) {
            // close previous </ul>
            if( $last_category != 0 ) echo "</ul>";
    
            // new title
            echo "<h1>" . $row['drinks_category_title'] . "</h1>";
    
            // new <ul>
            echo "<ul>";
    
            $last_category = $row['drinks_category_id'];
        }
    
        echo "<li>" . $row['drink_name'] . "</li>";
    }
    
    // close last </ul>
    if( $last_category != 0 ) echo "</ul>";
    
    0 讨论(0)
  • 2021-01-21 21:02

    Update your while loop to the following:

    while ($row = $result->fetch_assoc()) {
    
    if($row['drinks_category_id'] != $last_category) {
     if($last_category != 0) echo '</ul>';
     echo "<h1>" . $row['drinks_category_title'] . "</h1>";
     echo "<ul>";
    }
    
    echo "<li>" . $row['drink_name'] . "</li>";
    $last_category = $row['drinks_category_id'];
    
    }
    if($last_category != 0) echo "</ul>";
    
    0 讨论(0)
  • 2021-01-21 21:08

    Instead of having 3 tables, you could just add a category_id to your drinks table, just to simplify things. Then you can do this:

    SELECT drink_name, (SELECT drnk_category_title FROM drinks_category WHERE drink_category_id = drink_category // THE COLUMN I SUGGESTED //) AS title FROM drinks
    

    And then you can loop the result and build the nodes you desire really easily

    0 讨论(0)
提交回复
热议问题