php - Collapse on unique value which adding up the second in 2D array -
i have loop adds array of 2 values main array.
how can merge of arrays in main array have same first values while @ same time add values of second?
$maindata = array() ; //loop... $cres = $dbh->query("select overdue _credit_control_overdue entityid = $entityid") ; $currentowed = $cres->fetchcolumn() ; $dbh->exec("replace _credit_control_overdue (entityid, overdue) values ('$entityid', '$remaining')") ; $totalremaining += $remaining ; array_push($maindata, array($entityid, $remaining)) ; //end of loop
in many cases $entityid same, , $remaining different.
now need function similar array_unique leave me unique $entityid $remaining values added up, left e.g. 2339, 83572.60.
hope have explained clearly!
this output 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 first build associative array (hash) using $entityid keys (which give unique entry each one) , accumulated totals of $remaining values:
// initialise hash before looping $perentitytotals = array(); /* loop ... */ // add $remaining value appropriate entity's total // if key doesn't yet exist, created value $remaining $perentitytotals[$entityid] += $remaining; /* end loop */
to re-format asked for, you'll need manipulate hash:
$maindata = array(); foreach ( $perentitytotals $entityid => $total ) { $maindata[] = array($entityid, $total); }
the below equivalent, harder read:
$maindata = array_map( null, // see example #4 on http://php.net/array_merge array_keys($perentitytotals), array_values($perentitytotals) );
Comments
Post a Comment