PHP/MySQL group results by column(PHP/MySQL 按列分组结果)
问题描述
为了尽可能少的保留SQL语句,我想从MySQL做select set:
in order to keep as few SQL statements as possible, I want to do select set from MySQL:
SELECT * FROM products WHERE category IN (10,120,150,500) ORDER BY category,id;
现在,我有以下方式的产品列表:
Now, I have list of products in following manner:
CATEGORY
- product 1
- product 2
CATEGORY 2
- product 37
...
处理 MySQL 结果的最佳和最有效的方法是什么?
What's the best and most efficent way to process MySQL result?
我认为类似(伪 PHP)
I thought something like (pseudo PHP)
foreach ($product = fetch__assoc($result)){
$products[$category][] = $product;
}
然后在输出时,做foreach循环:
and then when outputting it, do foreach loop:
foreach($categories as $category){
foreach($products[$category] as $product){
$output;
}
}
这是最好的,还是像mysql_use_groupby
之类的神奇东西?
Is this the best, or is something magical like mysql_use_groupby
or something?
推荐答案
就像 mluebke
评论的那样,使用 GROUP 意味着您只能获得每个类别的一个结果.根据您提供的列表作为示例,我认为您想要这样的东西:
Like mluebke
commented, using GROUP means that you only get one result for each category. Based on the list you gave as an example, I think you want something like this:
$sql = "SELECT * FROM products WHERE category IN (10,120,150,500) GROUP BY category ORDER BY category, id";
$res = mysql_query($sql);
$list = array();
while ($r = mysql_fetch_object($res)) {
$list[$r->category][$r->id]['name'] = $r->name;
$list[$r->category][$r->id]['whatever'] = $r->whatever;
// etc
}
然后遍历数组.示例:
foreach ($list as $category => $products) {
echo '<h1>' . $category . '</h1>';
foreach ($products as $productId => $productInfo) {
echo 'Product ' . $productId . ': ' . $productInfo['name'];
// etc
}
}
这篇关于PHP/MySQL 按列分组结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP/MySQL 按列分组结果
基础教程推荐
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01