Group Array Data by Column and Sum Another Column for Associative Array
Given an array of data, such as:
$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], ];
The goal is to group the data based on the 'name' column and sum the 'amount' values within each group to form a flat associative array. The expected output is:
array ( 'Bank BRI' => 34534534, 'Bank BCA' => 1435773657, 'Bank CIMB Niaga' => 1338303418, 'Bank BNI' => 124124, 'Bank Mandiri' => 0, 'Bank Permata' => 352352353, )
Solution:
$bankTotals = array(); foreach ($array as $amount) { $bankTotals[$amount['name']] += $amount['amount']; }
This code initializes an empty array called $bankTotals. It then iterates over the input array, accessing each sub-array representing a row of data. For each row, it adds the 'amount' value to the corresponding 'name' key in the $bankTotals array. This process effectively groups rows by 'name' and sums the 'amount' values accordingly.
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 to Create an Associative Array?. For more information, please follow other related articles on the PHP Chinese website!