tags:

views:

95

answers:

2

I have an array in the format:

array (
   '1' => array (
      'id' => '2',
      'qty' => '4'
   ),
   '2' => array (
      'id' => '1',
      'qty' => '1'
   ),
   '3' => array (
      'id' => '2',
      'qty' => '3'
   ),
   '4' => array (
      'id' => '4',
      'qty' => '6'
   )
);

And want to find all duplicates of the column 'id', and to combine them into one (adding the values for 'qty' together).

Is there a better way to do this than a two foreach's? - it seems a bit too brute-forcey for me.

+3  A: 

Not pretty, but I think it does what it should (edited to maintain format):

$id = array();
foreach($array as $v) {
    if( $id[$v['id']] ) {
        $id[$v['id']]['qty'] += $v['qty'];
    } else {
        $id[$v['id']] = $v;
    }
}

// Optional reset keys
// $id = array_values($id);
// Optional sort keys in ascending order
// ksort($id);

print_r($id);

Gives:

Array
(
    [2] => Array
        (
            [id] => 2
            [qty] => 7
        )
    [1] => Array
        (
            [id] => 1
            [qty] => 1
        )
    [4] => Array
        (
            [id] => 4
            [qty] => 6
        )
)
Gordon
Unfortunately the array has more elements that need to be preserved - otherwise I'd use it. :(
Meep3D
@Meep3d is only quantity changing or can the other elements for one id change too? For instance id=1, qty=2, foo=3 but also id=1, qty=4, foo=5? If so, how would foo have to be treated then?
Gordon
@Meep3d updated again. Should do what you are looking for now.
Gordon
+2  A: 

You could change this a little to maintain the format, but this is basically the way to do it.

$items_by_id = array();
foreach($array as $item)
{
    if(!isset($items_by_id[$item['id']]))
    {
       $items_by_id[$item['id']] = $item['qty'];
    }
    else
    {
       $items_by_id[$item['id']] += $item['qty'];
    }

}
Chacha102