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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 08:10:02807browse

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

Grouping 2D Array Row Data by Column and Summing Another Column

In analyzing tabular data, it often becomes necessary to consolidate rows based on shared values in specific columns while performing calculations on other columns. Enter the challenge of grouping 2D array rows and summing values from a different column.

Problem Statement:

You are given a 2D array where each row represents a data entry. The goal is to group these rows by a specified grouping column (e.g., 'dd') and sum the values from another column (e.g., 'quantity') within each group. The result should be a reduced 2D array with unique grouping values and the corresponding summed column values.

Example:

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

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

Solution:

To tackle this problem, follow these steps:

  1. Iterate over each row: Traverse the input 2D array row by row.
  2. Check for existing group: Determine if a group for the current row's grouping value ('dd') already exists in an output array.
  3. Create new group if necessary: If no group exists for the current row's grouping value, create a new entry in the output array with the grouping value and an initial 'quantity' value of 0.
  4. Accumulate quantity: Increment the 'quantity' value of the existing or newly created group by the current row's 'quantity' value.
  5. Extract final array: Convert the output array back to a numerically indexed format to match the desired result.

Here's an example implementation in PHP:

$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);

This solution efficiently groups rows by the specified column, accumulates column values within each group, and produces a reduced 2D array as the desired result.

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