Home >Backend Development >PHP Tutorial >How to Group and Sum Array Data by Column in PHP?
Problem:
Given an array containing key-value pairs, group data based on the values of a specific column and sum data from another column. For example, if you have the following array:
$array = [ ['name' => 'Bank BRI', 'amount' => 0], ['name' => 'Bank BRI', 'amount' => 0], ['name' => 'Bank BCA', 'amount' => 1412341234], ['name' => 'Bank CIMB Niaga', 'amount' => 532532552], ['name' => 'Bank BRI', 'amount' => 34534534], ['name' => 'Bank CIMB Niaga', 'amount' => 453425243], ['name' => 'Bank BRI', 'amount' => 0], ['name' => 'Bank BNI', 'amount' => 124124], ['name' => 'Bank CIMB Niaga', 'amount' => 352345623], ['name' => 'Bank BCA', 'amount' => 23432423], ['name' => 'Bank Mandiri', 'amount' => 0], ['name' => 'Bank BCA', 'amount' => 0], ['name' => 'Bank BCA', 'amount' => 0], ['name' => 'Bank Permata', 'amount' => 352352353], ];
Solution:
To group the data based on the 'name' column and sum the data in the 'amount' column, follow these steps:
After iterating over the entire input array, the $bankTotals array will contain the grouped data with the bank names as keys and the summed amounts as values.
Here's the code to achieve the desired output:
$bankTotals = array(); foreach($array as $amount) { $bankTotals[$amount['name']] += $amount['amount']; } print_r($bankTotals);
Output:
Array ( [Bank BRI] => 34534534 [Bank BCA] => 1435773657 [Bank CIMB Niaga] => 1338303418 [Bank BNI] => 124124 [Bank Mandiri] => 0 [Bank Permata] => 352352353 )
The above is the detailed content of How to Group and Sum Array Data by Column in PHP?. For more information, please follow other related articles on the PHP Chinese website!