Home > Enterprise >  how to group array by given month and sum of total?
how to group array by given month and sum of total?

Time:09-19

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

Expected Result:

Array
(
[0] => Array
(
[month] => Aug-22
[totalAmount] => 3254
)
[1] => Array
(
[month] => Sep-22
[totalAmount] => 3254
)
)

CodePudding user response:

This is classic problem to use 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);

run php online

  •  Tags:  
  • php
  • Related