PHP和MYSQL:使用group by作为类别

sam*_*sam 6 php mysql

我的数据库具有以下设置

productid | productname | category id
Run Code Online (Sandbox Code Playgroud)

我想像这样输出它们:

category #1
item 1 
item 2
item 3

category #2
item 1 
item 2
item 3
Run Code Online (Sandbox Code Playgroud)

我把它们组合在一起使用,并且工作正常,但我想循环遍历每个组并显示该组的内容.我该怎么做?

Bil*_*win 18

我建议只需要一个简单的查询来获取所有行,按类别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";
}

?>
Run Code Online (Sandbox Code Playgroud)


2nd*_*boy 8

这应该工作:

$categories = array();
$result= mysql_query("SELECT category_id, product_name  FROM `table` GROUP BY `catagory_id` ORDER BY `catagory_id`");
while($row = mysql_fetch_assoc($result)){
    $categories[$row['category_id']][] = $row['product_name'];
}

// any type of outout you like
foreach($categories as $key => $category){
    echo $key.'<br/>';
    foreach($category as $item){ 
        echo $item.'<br/>';
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以自己设计的输出.您只需将所有内容添加到多维数组中,并将类别ID作为第一级键.

编辑:结果数组可能如下所示:

$categories = array(
    'cateogy_id_1' => array(
        1 => 'item_1',
        2 => 'item_2',
        ...
    ),
    'cateogy_id_2' => array(
        1 => 'item_1',
        2 => 'item_2',
        ...
    ),
    ....
);
Run Code Online (Sandbox Code Playgroud)