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

时间:2013-05-26 00:18:37

标签: php database loops mysqli

我在尝试获取嵌套的< ul>在一个while循环中。我不确定这是否可能,所以我愿意接受替代方案。

Here's a quick image of what my database looks like and what i'm trying to achieve.

这是我的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

这是我的输出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'];

}

我正在使用mysqli和php。提前谢谢!

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您可以将category_id添加到您的饮料表中,而不是拥有3个表,只是为了简化操作。然后你可以这样做:

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

然后你可以循环结果并轻松构建你想要的节点

答案 2 :(得分:0)

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