How to Group Rows in a 2D Array by One Column and Sum Another?

Susan Sarandon
Release: 2024-11-23 01:45:15
Original
834 people have browsed it

How to Group Rows in a 2D Array by One Column and Sum Another?

Reducing a 2D Array by Grouping Rows by One Column and Summing Another within Each Group

In this scenario, you seek to manipulate a 2D array by organizing its rows based on a specific column while aggregating the values of another column within each group created.

To address this need, consider employing an iterative approach through the rows of the input array:

$in = array(
    ['quantity' => 5, 'dd' => '01-Nov-2012'],
    ['quantity' => 10, 'dd' => '01-Nov-2012'],
    ['quantity' => 3, 'dd' => '02-Nov-2012'],
    ['quantity' => 4, 'dd' => '03-Nov-2012'],
    ['quantity' => 15, 'dd' => '03-Nov-2012'],
);
Copy after login

Create an empty output array:

$out = array();
Copy after login

Now, traverse each row:

foreach ($in as $row) {
Copy after login

Within each row, check if the dd value is already present in the $out array:

if (!isset($out[$row['dd']])) {
Copy after login

If not, create a new entry for the dd value with initialized 'quantity':

$out[$row['dd']] = array(
    'dd' => $row['dd'],
    'quantity' => 0,
);
Copy after login

Regardless, update the quantity value by adding the current row's quantity:

$out[$row['dd']]['quantity'] += $row['quantity'];
Copy after login

Finally, numerically index the $out array to achieve the desired reduced 2D array:

$out = array_values($out);
Copy after login

As a result, you obtain the summarized array with grouped rows:

var_dump($out);

[
    ['quantity' => 15, 'dd' => '01-Nov-2012'],
    ['quantity' => 3, 'dd' => '02-Nov-2012'],
    ['quantity' => 19, 'dd' => '03-Nov-2012'],
]
Copy after login

The above is the detailed content of How to Group Rows in a 2D Array by One Column and Sum Another?. 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