提问人:Erdal Bakkal 提问时间:12/20/2014 最后编辑:ADysonErdal Bakkal 更新时间:4/12/2023 访问量:2232
如何在 PHP 中使用 while 循环按 ID 列出部分中的数据?[已结束]
How can I list data in sections by an ID, with a while loop in PHP? [closed]
问:
我有一个包含以下列的 mysql 表:
series_id, series_color, product_name
在输出中,我想按部分列出数据,每个部分一个部分,如下所示:series_id
A12 Series Product
- Milk
- Tea
- sugar
- water
B12 Series Product
- Water
- Banana
- Cofee
- Tea
答:
3赞
Barmar
12/20/2014
#1
对结果进行排序,以便所有具有相同值的产品将放在一起。series_id
$stmt = $pdo->prepare("SELECT series_id, product_name
FROM yourTable
ORDER BY series_id");
$stmt->execute();
然后,在显示结果时,显示 Series 标题,并在更改时启动一个新标题:<ul>
$last_series = null;
echo "<ul>\n";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($row['series_id'] != $last_series) {
if ($last_series) {
echo "</ul></li>\n";
}
echo "<li>" . $row['series_id'] . " Series Product\n";
echo "<ul>\n";
$last_series = $row['series_id'];
}
echo "<li>" . $row['product_name'] . "</li>\n";
}
if ($last_series) {
echo "</li>\n";
}
echo "</ul>\n";
上一个:什么是差一错误,如何解决?
评论