Home >Backend Development >PHP Tutorial >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'], );
Create an empty output array:
$out = array();
Now, traverse each row:
foreach ($in as $row) {
Within each row, check if the dd value is already present in the $out array:
if (!isset($out[$row['dd']])) {
If not, create a new entry for the dd value with initialized 'quantity':
$out[$row['dd']] = array( 'dd' => $row['dd'], 'quantity' => 0, );
Regardless, update the quantity value by adding the current row's quantity:
$out[$row['dd']]['quantity'] += $row['quantity'];
Finally, numerically index the $out array to achieve the desired reduced 2D array:
$out = array_values($out);
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'], ]
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!