我想从数据库表中选择行,并使用 PHP 而不是 SQL 基于参数(在本例中为按项目)对它们进行分组。
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 item
PHP :
1 shoes joe
2 pants joe //count 2
3 hat joe
我确信有一个 PHP 数组函数可以实现这个功能,我只是不熟悉,你觉得呢?
最简单的方法是利用数组键的唯一性:
$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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)