How can I add array values ​​by unique key?

advertisements

For example

array (
product1_quantity => 5,
product1_quantity => 1,
product2_quantity => 3,
product2_quantity => 7,
product3_quantity => 2,
)

with result:

product1_quantity - 6,
product2_quantity - 10,
product3_quantity - 2

Thanx!


sorry, guys

stupid example, instead this really

Array ( [0] => Array ( [product1] => 7 ) [1] => Array ( [product1] => 2 ) [2] => Array ( [product2] => 3 ) )

?


Pull items off two at a time, and add to hash.

my @array = (
        product1_quantity => 5,
        product1_quantity => 1,
        product2_quantity => 3,
        product2_quantity => 7,
        product3_quantity => 2,
);
my %sums;
while (@array and my ($k,$v) = (shift(@array),shift(@array)) ) {
        $sums{$k} += $v;
}