Group Array Data Using SUM Calculation to Obtain a Flat Associative Array
In the provided scenario, you need to group data based on a specific column ("name") and sum values from another column ("amount") to form a flat associative array.
To achieve this, initially, you need to assign the appropriate values to the $amountsArray. Once this is established, you can proceed with the grouping and summation process.
Here's the code:
$bankTotals = array(); foreach ($amountsArray as $amount) { $bankTotals[$amount['name']] += $amount['amount']; }
This code snippet iterates through the $amountsArray and accumulates the 'amount' value for each unique 'name'. The result, $bankTotals, will be an array with bank names as keys and their respective total amounts as values.
For instance:
array ( 'Bank BRI' => 34534534, 'Bank BCA' => 1435773657, 'Bank CIMB Niaga' => 1338303418, 'Bank BNI' => 124124, 'Bank Mandiri' => 0, 'Bank Permata' => 352352353, )
You can further iterate through $bankTotals to display the grouped data:
foreach ($bankTotals as $name => $amount) { echo $name . "....." . $amount . "\n"; }
This will print the bank names and their respective total amounts in the format:
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 to Create a Flat Associative Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!