by php 数组按月group_如何GROUP BY和SUM PHP数组?

这篇博客探讨了如何使用PHP处理数组,按evaluation_category_id进行分组,并对每个组的score和itemMaxPoint字段进行求和操作。文章中提供了代码示例,但指出该示例存在错误,未正确实现分组求和。作者请求帮助找出并修正问题。
摘要由CSDN通过智能技术生成

如何按evaluation_category_id对此数组进行GROUP BY和SUM

Array

(

[0] => Array

(

[id] => 60

[evaluation_category_id] => 3

[score] => 15

[itemMaxPoint] => 20

)

[1] => Array

(

[id] => 61

[evaluation_category_id] => 2

[score] => 10

[itemMaxPoint] => 20

)

[2] => Array

(

[id] => 62

[evaluation_category_id] => 1

[score] => 5

[itemMaxPoint] => 20

)

[3] => Array

(

[id] => 63

[evaluation_category_id] => 1

[score] => 50

[itemMaxPoint] => 200

)

[4] => Array

(

[id] => 64

[evaluation_category_id] => 2

[score] => 150

[itemMaxPoint] => 200

)

[5] => Array

(

[id] => 65

[evaluation_category_id] => 3

[score] => 30

[itemMaxPoint] => 50

)

.

.

.

)

所以我得到这样的数组

Array

(

[0] => Array

(

[evaluation_category_id] => 3

[score] => 45

[itemMaxPoint] => 70

)

[1] => Array

(

[evaluation_category_id] => 2

[score] => 160

[itemMaxPoint] => 220

)

[2] => Array

(

[evaluation_category_id] => 1

[score] => 55

[itemMaxPoint] => 220

)

}

我试过这个,但它不起作用。请纠正我在哪里做错了

public function test($data) {

$groups = array();

foreach ($data as $item) {

$key = $item['evaluation_category_id'];

if (!isset($groups[$key])) {

$groups[$key] = array(

'id' => $key,

'score' => $item['score'],

'itemMaxPoint' => $item['itemMaxPoint'],

);

} else {

$groups[$key]['score'] = $groups[$key]['score'] + $item['score'];

$groups[$key]['itemMaxPoint'] = $groups[$key]['itemMaxPoint'] +$item['itemMaxPoint'];

}

}

return $groups;

}

输出

Array

(

[2] => Array

(

[id] => 2

[score] => 121 //121 because the given array is different.but its actually SUM all values of score

[itemMaxPoint] => 300

)

)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值