Generally, the GROUP BY clause and SUM() function are used in the database to sort the records. The GROUP BY statement group records by the same values and returns filtered records. The SUM() is an aggregate function used by the GROUP BY statement. The GROUP BY and SUM operations can be integrated into the data list at the code level in PHP.
Use the PHP array_reduce() function to GROUP BY and SUM values of an array in PHP. In this example, we will show you how to group array by key and sum values using PHP. It helps to sum the values of an array with the same keys in PHP.
In the following code snippet, we will group the array by category_id
and sum score
values with PHP.
$array = array(
array(
'id' => 1,
'category_id' => 5,
'score' => 321
),
array(
'id' => 2,
'category_id' => 2,
'score' => 123
),
array(
'id' => 3,
'category_id' => 5,
'score' => 567
),
array(
'id' => 4,
'category_id' => 2,
'score' => 878
),
array(
'id' => 5,
'category_id' => 5,
'score' => 621
)
);
$result = array_reduce($array, function($carry, $item){
if(!isset($carry[$item['category_id']])){
$carry[$item['category_id']] = ['category_id'=>$item['category_id'],'score'=>$item['score']];
} else {
$carry[$item['category_id']]['score'] += $item['score'];
}
return $carry;
});
The following array will return after GROUP BY and SUM operations.
Array
(
[5] => Array
(
[category_id] => 5
[score] => 1509
)
[2] => Array
(
[category_id] => 2
[score] => 1001
)
)