Home >Backend Development >PHP Tutorial >How to Group and Sum Array Data to Create a Flattened Associative Array?
Grouping Array Data and Summing Values for Flattened Associative Array
Given an array of associative data, the challenge involves grouping elements by one column (e.g., 'name') and summing values from another column (e.g., 'amount'). The result is a flattened associative array with groups as keys and summed amounts as values.
Provided Array Data
$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 array data by 'name' and sum the 'amount' values, follow these steps:
Code:
$bankTotals = array(); foreach($array as $amount) { $bankTotals[$amount['name']] += $amount['amount']; }
Output:
array ( 'Bank BRI' => 34534534, 'Bank BCA' => 1435773657, 'Bank CIMB Niaga' => 1338303418, 'Bank BNI' => 124124, 'Bank Mandiri' => 0, 'Bank Permata' => 352352353, )
The $bankTotals array now contains the grouped and summed data, with bank names as keys and total amounts as values. This flattened associative array is ready for further use in your application.
The above is the detailed content of How to Group and Sum Array Data to Create a Flattened Associative Array?. For more information, please follow other related articles on the PHP Chinese website!