Home  >  Article  >  Backend Development  >  How to Group Rows by a Specific Column and Sum Another Column in a 2D Array?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-17 02:33:03648browse

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

Grouping Data and Summing Columns in a 2D Array

In data processing scenarios, you may encounter the need to group rows of a 2D array based on a specified column and then accumulate the values in another column within each group.

Problem Statement:

Given an input array like the one shown below:

[
    ['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'],
]

You want to group the rows by the 'dd' column and sum the 'quantity' values within each group. The expected output is:

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

Solution:

To achieve this, we can use a simple looping mechanism. Starting from the first row, we check if the 'dd' value is already present in the output array. If not, we create a new entry for that 'dd' and initialize the 'quantity' to 0.

Then, for each row, we add the 'quantity' to the corresponding group in the output array. We repeat this process until all rows have been processed. Finally, we convert the output array to numerical indexing using array_values().

The following PHP code demonstrates the solution:

$in = array(array()); // your input
$out = array();
foreach ($in as $row) {
    if (!isset($out[$row['dd']])) {
        $out[$row['dd']] = array(
            'dd' => $row['dd'],
            'quantity' => 0,
        );
    }
    $out[$row['dd']]['quantity'] += $row['quantity'];
}
$out = array_values($out); // make the out array numerically indexed
var_dump($out);

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