Group and Sum 2D Array Data by Columns
In this programming scenario, the objective is to group rows of a 2D array by one column's values (e.g., 'dd') and subsequently sum the values of another column ('quantity') within each group. The result is a reduced 2D array with unique 'dd' values and aggregated quantity information.
Example:
Consider the following input 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'], ]
The desired output array would be:
[ ['quantity' => 15, 'dd' => '01-Nov-2012'], ['quantity' => 3, 'dd' => '02-Nov-2012'], ['quantity' => 19, 'dd' => '03-Nov-2012'], ]
Solution using PHP:
To achieve this data transformation, we can utilize PHP's built-in arrays and looping capabilities:
// Input array $in = array(array()); // Create output array $out = array(); // Iterate through input rows foreach ($in as $row) { // Check if 'dd' key exists in output array if (!isset($out[$row['dd']])) { // Initialize entry for 'dd' with empty quantity $out[$row['dd']] = array( 'dd' => $row['dd'], 'quantity' => 0, ); } // Accumulate quantity for 'dd' key $out[$row['dd']]['quantity'] += $row['quantity']; } // Adjust output array to numerical indexing $out = array_values($out); // Display output array var_dump($out);
The above is the detailed content of How to Group and Sum Data in a 2D Array by Column in PHP?. For more information, please follow other related articles on the PHP Chinese website!