I have a loop that adds an array of two values to a main array.
How can I merge all of the arrays in the main array that have the same first values while at the same time add up the values of the second?
$mainData = array() ;
//Loop...
$cRes = $dbh->query("SELECT overdue FROM _credit_control_overdue WHERE entityID = $entityId") ;
$currentOwed = $cRes->fetchColumn() ;
$dbh->exec("REPLACE INTO _credit_control_overdue (entityID, overdue) VALUES ('$entityId', '$remaining')") ;
$totalRemaining += $remaining ;
array_push($mainData, array($entityId, $remaining)) ;
//End of loop
In many cases $entityId will be the same, and $remaining will be different.
Now I need a function similar to array_unique that will leave me with a unique $entityId but with all the $remaining values added up, so I am left with e.g. 2339, 83572.60.
Hope I have explained this clearly!
This is the output I desire:
Array ( [0] => Array ( [0] => 2499 [1] => 5314.50 ) [1] => Array ( [0] => 639 [1] => 75.00 ))
i.e Array ( [0] => UNIQUEID [1] => SUM )
The best way to do this is probably to first build an associative array (hash) using the $entityId as the keys (which will give you a unique entry for each one) and the accumulated totals of $remaining as the values:
To re-format this as you originally asked for, you’ll then need to manipulate the hash:
The below is equivalent, but somewhat harder to read: