Group 2d array’s row data by one column and sum another column within each group to produce a reduced 2d array

Just loop trough the rows, and add up the quantities in a different array indexed by the dd values.

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

Leave a Comment