PHP/MySQL 按列对结果进行分组
为了保留尽可能少的 SQL 语句,我想从 MySQL 中进行选择集:
SELECT * FROM products WHERE category IN (10,120,150,500) ORDER BY category,id;
现在,我按以下方式列出了产品:
CATEGORY
- product 1
- product 2
CATEGORY 2
- product 37
...
处理 MySQL 结果的最佳和最有效的方法是什么?
我想到了类似(伪PHP)的东西
foreach ($product = fetch__assoc($result)){
$products[$category][] = $product;
}
,然后在输出它时,执行foreach循环:
foreach($categories as $category){
foreach($products[$category] as $product){
$output;
}
}
这是最好的,还是像mysql_use_groupby
之类的神奇东西?
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
...
What's the best and most efficent way to process MySQL result?
I thought something like (pseudo PHP)
foreach ($product = fetch__assoc($result)){
$products[$category][] = $product;
}
and then when outputting it, do foreach loop:
foreach($categories as $category){
foreach($products[$category] as $product){
$output;
}
}
Is this the best, or is something magical like mysql_use_groupby
or something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就像
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:And then loop through the array. Example:
不,我认为你的解决方案是解决这个问题的最佳方案。看来对你来说重要的是稍后的输出,所以你应该坚持你的方法。
Nope, I think your solution is the best for this problem. It seems that what's important for you is the output later on, so you should stick with your approach.
您想要获取类别列表还是实际上将所有产品分组到类别中?
如果是后者,最好这样做:
然后在 PHP 中,您可以遍历数组(伪代码):
这将为您留下 $cats 作为数组,其中包含已排序的产品。
Do you want to get a list of categories or actually get all products grouped into categories?
If it's the latter, best to do:
Then in PHP you can go through the array (psuedo code):
Which will leave you with $cats as an array with products sorted into it.