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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.