简体   繁体   English

如何在while循环中创建嵌套列表?

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

I'm having trouble trying to get a nested < ul > inside of a while loop. 我在尝试在while循环内获取嵌套的<ul>时遇到麻烦。 I'm not sure if this even possible so i'm open to alternatives. 我不确定这是否可能,所以我愿意接受替代方案。

Here's a quick image of what my database looks like and what i'm trying to achieve. 这是我的数据库的外观以及我正在尝试实现的快速图像。

Here's my sql 这是我的sql

SELECT * 
FROM drinks_category, drinks_lookup, drinks 
WHERE drinks.drink_id = drinks_lookup.drink_id 
AND drinks_lookup.drinks_category_id = drinks_category.drinks_category_id
ORDER BY drinks_category.drinks_category_title

Here's my output php 这是我的输出PHP

$result = $conn->query($sql) or die(mysqli_error());

$last_category = 0;

while ($row = $result->fetch_assoc()) {

    if($row['drinks_category_id'] != $last_category) {
     echo "<h1>" . $row['drinks_category_title'] . "</h1>";
    }

    echo "<p>" . $row['drink_name'] . "</p>";
    $last_category = $row['drinks_category_id'];

}

Im using mysqli and php. 我正在使用mysqli和php。 Thanks in advance! 提前致谢!

Update your while loop to the following: while循环更新为以下内容:

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

Instead of having 3 tables, you could just add a category_id to your drinks table, just to simplify things. 只需3个表,您就可以在饮料表中添加category_id,以简化操作。 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 然后您可以循环结果并真正轻松地构建所需的节点

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM