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:
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!