PHP& MYSQL:对类别使用分组依据 [英] PHP & MYSQL: using group by for categories

查看:49
本文介绍了PHP& MYSQL:对类别使用分组依据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库具有以下设置

My database has the following setup

productid | productname | category id

我想像这样输出它们:

category #1
item 1 
item 2
item 3

category #2
item 1 
item 2
item 3

我按组使用它们,并且效果很好,但是我想遍历每个组并显示该组的内容.我该怎么做?

I used group by the group them together and that works fine, but I want to loop through each group and display the contents of that group. How would I do this?

推荐答案

我建议只使用一个简单的查询来获取所有行,并按类别ID进行排序.仅当类别的值从上一行更改时,才输出类别.

I'd recommend just a simple query to fetch all the rows, sorted by category id. Output the category only if its value changes from the previous row.

<?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&amp; MYSQL:对类别使用分组依据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆