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

How to Group and Sum Array Data to Create a Flat Associative Array in PHP?

Susan Sarandon
Release: 2024-12-07 06:50:11
Original
320 people have browsed it

How to Group and Sum Array Data to Create a Flat Associative Array in PHP?

Group Array Data Using SUM Calculation to Obtain a Flat Associative Array

In the provided scenario, you need to group data based on a specific column ("name") and sum values from another column ("amount") to form a flat associative array.

To achieve this, initially, you need to assign the appropriate values to the $amountsArray. Once this is established, you can proceed with the grouping and summation process.

Here's the code:

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

This code snippet iterates through the $amountsArray and accumulates the 'amount' value for each unique 'name'. The result, $bankTotals, will be an array with bank names as keys and their respective total amounts as values.

For instance:

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

You can further iterate through $bankTotals to display the grouped data:

foreach ($bankTotals as $name => $amount) {
  echo $name . "....." . $amount . "\n";
}
Copy after login

This will print the bank names and their respective total amounts in the format:

Bank BRI.....34534534
Bank BCA.....1435773657
Bank CIMB Niaga.....1338303418
Bank BNI.....124124
Bank Mandiri.....0
Bank Permata.....352352353
Copy after login

The above is the detailed content of How to Group and Sum Array Data to Create a Flat Associative Array in PHP?. 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