Home >Backend Development >PHP Tutorial >How to Group and Sum Array Data by Column in PHP?

How to Group and Sum Array Data by Column in PHP?

DDD
DDDOriginal
2024-12-06 13:52:12968browse

How to Group and Sum Array Data by Column in PHP?

Group Array Data on One Column and Sum Data from Another Column to Form a Flat Associative Array

Problem:

Given an array containing key-value pairs, group data based on the values of a specific column and sum data from another column. For example, if you have the following array:

$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 data based on the 'name' column and sum the data in the 'amount' column, follow these steps:

  1. Initialize an empty array called $bankTotals. This array will store the grouped data.
  2. Iterate over the input array using a foreach loop.
  3. For each element in the array, check if the bankTotals array already contains a key matching the 'name' value of the current element.
  4. If the bankTotals array does not contain a key matching the current 'name' value, create a new key with that value and set its value to 0.
  5. Add the amount value of the current element to the corresponding key in the bankTotals array.

After iterating over the entire input array, the $bankTotals array will contain the grouped data with the bank names as keys and the summed amounts as values.

Here's the code to achieve the desired output:

$bankTotals = array();
foreach($array as $amount)
{
  $bankTotals[$amount['name']] += $amount['amount'];
}

print_r($bankTotals);

Output:

Array
(
    [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 by Column in PHP?. 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