Home > Backend Development > PHP Tutorial > How to Group and Sum Array Data by One Column to Create a Flat Associative Array?

How to Group and Sum Array Data by One Column to Create a Flat Associative Array?

Linda Hamilton
Release: 2024-12-04 21:14:15
Original
722 people have browsed it

How to Group and Sum Array Data by One Column to Create a Flat Associative Array?

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:

  1. Initialize an empty array called $bankTotals. This array will be used to store the grouped and summed data.
  2. Iterate through the input array using a foreach loop.
  3. For each element, extract the 'name' and 'amount' values.
  4. Check if the 'name' is already a key in $bankTotals.
  5. If the 'name' is not a key, add it to $bankTotals and set its value to the 'amount'.
  6. If the 'name' is already a key, increment the existing value by the 'amount'.
  7. Once the loop has completed, $bankTotals will contain the grouped and summed data in the desired format.

Example:

// Assuming $array is the input array
$bankTotals = array();
foreach ($array as $amount) {
  $bankTotals[$amount['name']] += $amount['amount'];
}
Copy after login

This code will generate an associative array such as the one presented in the problem statement.

Notes:

  • The = operator is used to increment the 'amount' value for each 'name' in $bankTotals.
  • You can use var_dump($bankTotals) to view the output array for debugging purposes.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template