Home >Backend Development >PHP Tutorial >How to Group and Sum Array Data to Create a Flattened Associative Array?

How to Group and Sum Array Data to Create a Flattened Associative Array?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 02:39:09906browse

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:

  1. Initialize an empty array called $bankTotals.
  2. Iterate over the $array using a foreach loop.
  3. For each element in the array, retrieve the 'name' and 'amount' keys.
  4. If the key doesn't exist in $bankTotals, set it to 0.
  5. Increment the 'amount' for the current bank name in $bankTotals.

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!

Statement:
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