gpt4 book ai didi

PHP & MySQL : using group by for categories

转载 作者:可可西里 更新时间:2023-11-01 06:38:53 25 4
gpt4 key购买 nike

我的数据库有以下设置

productid | productname | category id

我想像这样输出它们:

category #1
item 1
item 2
item 3

category #2
item 1
item 2
item 3

我通过将它们分组在一起来使用分组并且工作正常,但我想遍历每个组并显示该组的内容。我该怎么做?

最佳答案

我建议只使用一个简单的查询来获取所有行,并按类别 ID 排序。仅当其值与上一行相比发生变化时才输出类别。

<?php

$stmt = $pdo-> query("SELECT * FROM `myTable` ORDER BY categoryID");

$current_cat = null;
while ($row = $stmt->fetch()) {
if ($row["categoryID"] != $current_cat) {
$current_cat = $row["categoryID"];
echo "Category #{$current_cat}\n";
}
echo $row["productName"] . "\n";
}

?>

关于PHP & MySQL : using group by for categories,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2977213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com