如何使用PHP执行SQL的GROUP? [英] How to do SQL's GROUP BY using PHP?

查看:36
本文介绍了如何使用PHP执行SQL的GROUP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从数据库表中选择行,然后使用PHP而不是基于参数的SQL(在此情况下,按项目)对行进行分组.

I'd like to SELECT rows from a database table and group them using PHP instead of SQL based on a parameter (in this case by item).

SQL:

Clothes table

 id  item     owner
 1   shoes     joe 
 2   pants     joe
 3   hat       joe
 4   pants     joe
 5   hat       tom

SELECT * from Clothes where owner='joe'

 1   shoes     joe 
 2   pants     joe
 3   hat       joe
 4   pants     joe

这是我希望使用PHP而不是SQL的 GROUP BY项目

Here's how I'd like the results to look after using PHP instead of SQL's GROUP BY item

PHP:

 1   shoes     joe 
 2   pants     joe   //count 2
 3   hat       joe

我确定对此有一个PHP数组函数,我只是不熟悉,对吗?

I'm sure there is a PHP array function for this I'm just not familiar, thoughts?

推荐答案

最简单的方法是利用数组键的唯一性:

The easiest way is to exploit the uniqueness of array keys:

$grouped = array();

while ($row = $db->fetchResult()) {  // or however you get your data
    if (isset($grouped[$row['item']])) {
        $grouped[$row['item']]['count']++;
    } else {
        $grouped[$row['item']] = $row + array('count' => 1);
    }
}

这篇关于如何使用PHP执行SQL的GROUP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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