How to do SQL's GROUP BY using PHP?

◇◆丶佛笑我妖孽 提交于 2021-02-16 20:13:27

问题


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

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

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


回答1:


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);
    }
}



回答2:


Using pseucode for the database access functions, I believe this should work:

$sql = "SELECT * from Clothes where owner='joe'";
$res = query($sql);
$arr = array();    

while ($row = $res->fetch())
{
    $arr[] = $row['item'];
}

$arr = array_unique($arr);

You should note that this might give you a "sparse array" (in other words, there may be gaps in the keys). And as said in the comments, it's usually better to do this in SQL if you have that option. Even if that means executing two similar queries.




回答3:


function group($items, $field) {
    $return = array();

    foreach ($items as $item) {
        $key = $item[$field];

        if (isset($return[$key])) {
            $return[$key]['count']++;
        } else {
            $return[$key] = $item;
            $return[$key]['count'] = 1;
        }
    }

    return $return;
}

print_r(group($results, "item"));


来源:https://stackoverflow.com/questions/13129926/how-to-do-sqls-group-by-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!