Grouping and Summing Data in a 2D Array
In this scenario, you aim to group the rows of a 2D array based on a specific column's values and then sum another column's values within each group.
Input Data:
[ ['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'], ];
Implementation:
To achieve this, follow these steps:
For each row:
The following PHP code demonstrates this process:
$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 approach effectively groups the input data by the 'dd' column and sums the 'quantity' column values for each group, producing the desired output.
The above is the detailed content of How to Group and Sum Data in a 2D Array by Column?. For more information, please follow other related articles on the PHP Chinese website!