[英]how to group array by given month and sum of total?
I want to get result as sum of total and group by month, my array look like:我想将结果作为总数和按月分组的总和,我的数组如下所示:
Array
(
[0] => Array
(
[order_no] => 222
[month] => Aug-22
[totalAmount] => 2305
)
[1] => Array
([order_no] => 333
[month] => Aug-22
[totalAmount] => 945
)
[2] => Array
(
[order_no] => 1
[month] => Sep-22
[totalAmount] => 945
)
[3] => Array
(
[order_no] => 111
[month] => Sep-22
[totalAmount] => 2305
)
)
What I am trying to do: I want to group these data by MONTH and return the sum我正在尝试做的事情:我想按 MONTH 对这些数据进行分组并返回总和
Expected Result:预期结果:
Array
(
[0] => Array
(
[month] => Aug-22
[totalAmount] => 3254
)
[1] => Array
(
[month] => Sep-22
[totalAmount] => 3254
)
)
This is classic problem to use array_reduce
function:这是使用
array_reduce
function 的经典问题:
<?php
$arr = [
["order_no" => 222, "month" => "Aug-22", "totalAmount" => 2305],
["order_no" => 333, "month" => "Aug-22", "totalAmount" => 945],
["order_no" => 1, "month" => "Sep-22", "totalAmount" => 945],
["order_no" => 111, "month" => "Sep-22", "totalAmount" => 2305],
];
$res = array_reduce(
$arr,
function($acc, $order) {
if (isset($acc[$order['month']])) {
$acc[$order['month']]['totalAmount'] += $order['totalAmount'];
} else {
$acc[$order['month']] = [
"month" => $order['month'], "totalAmount" => $order['totalAmount']
];
}
return $acc;
},
[]
);
print_r($res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.