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

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

DDD
Release: 2024-12-16 12:15:17
Original
454 people have browsed it

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

Group Array Data by Column and Sum Another Column for Associative Array

Given an array of data, such as:

$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],
];
Copy after login

The goal is to group the data based on the 'name' column and sum the 'amount' values within each group to form a flat associative array. The expected output is:

array (
  'Bank BRI' => 34534534,
  'Bank BCA' => 1435773657,
  'Bank CIMB Niaga' => 1338303418,
  'Bank BNI' => 124124,
  'Bank Mandiri' => 0,
  'Bank Permata' => 352352353,
)
Copy after login
Copy after login

Solution:

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

This code initializes an empty array called $bankTotals. It then iterates over the input array, accessing each sub-array representing a row of data. For each row, it adds the 'amount' value to the corresponding 'name' key in the $bankTotals array. This process effectively groups rows by 'name' and sums the 'amount' values accordingly.

Output:

array (
  'Bank BRI' => 34534534,
  'Bank BCA' => 1435773657,
  'Bank CIMB Niaga' => 1338303418,
  'Bank BNI' => 124124,
  'Bank Mandiri' => 0,
  'Bank Permata' => 352352353,
)
Copy after login
Copy after login

The above is the detailed content of How to Group and Sum Array Data by Column in PHP to Create an 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template