3v4l.org

run code in 300+ PHP versions simultaneously
<?php function sumArray($array, $index, $col) { $returnArray = []; // temporary container // sanity checks if (!is_array($array)) { return 'error not an array'; } $firstRow = reset($array); if (!array_key_exists($index, $firstRow) || !array_key_exists($col, $firstRow)) { return 'error keys provided not found'; } foreach ($array as $value) { if (!isset($returnArray[$value[$index]])) { // initialize $returnArray[$value[$index]] = [$index => $value[$index], $col => 0]; } // add value $returnArray[$value[$index]][$col] += $value[$col]; } return $returnArray; } $products = array ( array("Id" => "000001", "Name" => "Cheese", "Quantity" => "10", "Price" => "10"), array("Id" => "000001", "Name" => "Cheese", "Quantity" => "20", "Price" => "20"), array("Id" => "000001", "Name" => "Cheese", "Quantity" => "10", "Price" => "30"), array("Id" => "000002", "Name" => "Ham", "Quantity" => "20", "Price" => "200"), array("Id" => "000002", "Name" => "Ham", "Quantity" => "9", "Price" => "100"), array("Id" => "000003", "Name" => "Baicon", "Quantity" => "40", "Price" => "900") ); $summedArray = sumArray($products, 'Id', 'Quantity'); print_r($summedArray);

preferences:
24.52 ms | 405 KiB | 5 Q