How can I sum the values โ€‹โ€‹of an array using a unique key?

for instance

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

with the result:

 product1_quantity - 6, product2_quantity - 10, product3_quantity - 2 

Thanx!


sorry guys

silly example, instead it really is

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

?

+4
source share
4 answers

Pull the elements two times and add to the 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; } 
+3
source

You need something similar to:

  use Data::Dumper; my @input = ( product1_quantity => 5, product1_quantity => 1, product2_quantity => 3, product2_quantity => 7, product3_quantity => 2, ); my %output; while (my $product = shift(@input) and my $quantity = shift(@input)) { $output{$product} += $quantity; } print Dumper %output; 

This spits out:

 $VAR1 = 'product2_quantity'; $VAR2 = 10; $VAR3 = 'product3_quantity'; $VAR4 = 2; $VAR5 = 'product1_quantity'; $VAR6 = 6; 

Be warned, though, if you have any undefs in your quantitative values, it will break a lot. You should have an even array of product pairs / numerical values.

+2
source
 new_array; foreach p in array: if(new_array.contains(p.key)) new_array[p.key] += p.value; else new_array[p.key] = p.value; 

new_array will contain the amounts

0
source

In Perl:

 my %hash = (); $hash{'product1_quantity'} += 5; $hash{'product1_quantity'} += 1; $hash{'product2_quantity'} += 3; $hash{'product2_quantity'} += 7; $hash{'product3_quantity'} += 2; say join ",\n", map { "$_ - $hash{$_}" } keys %hash; 

Exit:

 product2_quantity - 10, product3_quantity - 2, product1_quantity - 6 

The order is different, but you can make it be โ€œfineโ€ by adding sorting:

 say join ",\n", map { "$_ - $hash{$_}" } sort {$a cmp $b} keys %hash; 
0
source

Source: https://habr.com/ru/post/1305016/


All Articles