Group Array Data on One Column and Sum Data from Another Column for a Flat Associative Array
Problem:
Given an array of data with two columns, 'name' and 'amount,' how can you group the data by 'name' and sum the corresponding 'amount' values to form a flat associative array?
Desired Result:
The output array should contain the grouped names as keys and the summed amounts as values.
Solution:
To achieve the desired result, follow these steps:
Example:
// Assuming $array is the input array $bankTotals = array(); foreach ($array as $amount) { $bankTotals[$amount['name']] += $amount['amount']; }
This code will generate an associative array such as the one presented in the problem statement.
Notes:
The above is the detailed content of How to Group and Sum Array Data by One Column to Create a Flat Associative Array?. For more information, please follow other related articles on the PHP Chinese website!