2010-03-24 42 views
4

例如如何通過唯一鍵對數組值進行求和?

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

與結果:

product1_quantity - 6, 
product2_quantity - 10, 
product3_quantity - 2 

感謝名單!


抱歉,球員

笨例如,代替該真

陣列([0] =>數組([產品1] => 7) [1] =>數組([產品1 ] => 2) [2] => Array([product2] => 3) )

+2

嚴姆語?通常情況下,每個鍵只能有一個值。所以你提供的數組甚至不是有效的。 – 2010-03-24 16:11:39

+0

我不知道任何可能具有相同鍵值的語言。 – neo 2010-03-24 16:12:04

+0

看起來像perl,也許。 – Sorpigal 2010-03-24 16:12:29

回答

3

一次拉下兩個項目,並添加到散列。

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; 
} 
+0

哎呦,錯過了,這與其他答案基本相同,誰打了我兩個小時。抱歉! – kbenson 2010-03-24 19:16:55

0
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將包含款項

+0

這看起來不像Perl ... – 2010-04-02 04:41:30

+1

Perl沒有在原文中提及當我寫這篇文章時發佈 - 查看帖子的修訂歷史..「謝謝」-1 – Axarydax 2010-04-05 06:28:16

0

在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; 

輸出是:

product2_quantity - 10, 
product3_quantity - 2, 
product1_quantity - 6 

的順序是不同的,但你可以強制它是「在訂單「加入排序:

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

你想要類似於:

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; 

該吐出:

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

雖然被警告 - 如果你已經在你的數量有任何undefs值這是怎麼回事努力打破。您需要有一個偶數長度的產品/數量數量對數組。

相關問題