Jump to content

Combine array values with same indexes?


dijix316

Recommended Posts

Hopefully my posting title makes sense.

 

I have the results from a MSSQL query in an associative array. Here is a small example of what a few rows of my results may look like:

 

Array ([usrPK] => 22 [usrName] =>Bob [usrDate]=>08/12/09 [b][usrQty]=>2[/b])
Array ([usrPK] => 22 [usrName] =>Bob [usrDate]=>08/12/09 [b][usrQty]=>0.25[/b])
Array ([usrPK] => 10 [usrName] =>Billy [usrDate]=>08/12/09 [usrQty]=>1)

 

What I would like to have is:

 

Array ([usrPK] => 22 [usrName] =>Bob [usrDate]=>08/12/09 [b][usrQty]=>2.25[/b])
Array ([usrPK] => 10 [usrName] =>Billy [usrDate]=>08/12/09 [usrQty]=>1)

 

Basically Bob has two records on this date which I would like combined into one with the sum of array([usrQty]) value from the two results. Now I'd prefer to do this post SQL query, but if I can't how would I format my MSSQL query to accomplish this?

 

Thanks in advance for your help.

Link to comment
https://forums.phpfreaks.com/topic/170753-combine-array-values-with-same-indexes/
Share on other sites

<?php
$test = array(
Array ('usrPK' => 22, 'usrName' =>'Bob', 'usrDate'=>'08/12/09', 'usrQty'=>'2'),
Array ('usrPK' => 22, 'usrName' =>'Bob', 'usrDate'=>'08/12/09', 'usrQty'=>'0.25'),
Array ('usrPK' => 10, 'usrName' =>'Billy', 'usrDate'=>'08/12/09', 'usrQty'=>'1')
);
$out = array();
foreach ($test as $v){
if (isset($out[$v['usrPK']])) $out[$v['usrPK']]['usrQty']+=$v['usrQty']; else $out[$v['usrPK']]=$v;
}
print_r($out);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.