How to Sum and GROUP BY Values of an Array in PHP


0

In this tutorial we are going to Sum and GROUP BY Values of an Array in PHP

Normally, the SUM() function and GROUP BY clause are used in the database to sort the records. The GROUP BY statement group records by the similar values and returns filtered records. The SUM () function is a combined function used by the GROUP BY declaration. The SUM and GROUP BY operations can be unified into the data list in PHP.

Use of PHP array_reduce() function to SUM and GROUP BY values of an array in PHP. In this code, we will show you how to group array by key and sum values in PHP. It supports to sum the values of an array with the same keys in PHP.

In the following PHP 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 SUM and GROUP BY operations.

Array
(
    [5] => Array
        (
            [category_id] => 5
            [score] => 1509
        )

    [2] => Array
        (
            [category_id] => 2
            [score] => 1001
        )

)
Post Pagination


Like it? Share with your friends!

0
Developer

0 Comments