2015-11-03 99 views
0

我想知道什麼是合併一些具有相同值的數組的最佳方式。合併數組,但具有相同的值

我的輸出:

array (size=16) 
    'totalAttemps' => int 4 
    'totalSuccess' => int 4 
    'totalFailed' => int 0 
    'ituCount' => int 0 
    'pddSuc' => int 11543 
    'pddFailed' => int 0 
    'ituCount34' => int 0 
    'FAS10' => int 4 
    'FAS20' => int 4 
    'FAS40' => int 4 
    'FAS60' => int 4 
    'region' => string 'TEST' 
    'oneOne' => int 24 
    'sixSix' => int 48 
    'thirtySix' => int 120 
    'sixtySixty' => int 240 
array (size=16) 
    'totalAttemps' => int 1 
    'totalSuccess' => int 1 
    'totalFailed' => int 0 
    'ituCount' => int 0 
    'pddSuc' => int 5829 
    'pddFailed' => int 0 
    'ituCount34' => int 0 
    'FAS10' => int 1 
    'FAS20' => int 1 
    'FAS40' => int 1 
    'FAS60' => int 1 
    'region' => string 'TEST' 
    'oneOne' => int 6 
    'sixSix' => int 12 
    'thirtySix' => int 30 
    'sixtySixty' => int 60 

我想:

array (size=16) 
    'totalAttemps' => int 5 
    'totalSuccess' => int 5 
    'totalFailed' => int 0 
    'ituCount' => int 0 
    'pddSuc' => int 17372 
    'pddFailed' => int 0 
    'ituCount34' => int 0 
    'FAS10' => int 5 
    'FAS20' => int 5 
    'FAS40' => int 5 
    'FAS60' => int 5 
    'region' => string 'TEST' 
    'oneOne' => int 30 
    'sixSix' => int 60 
    'thirtySix' => int 150 
    'sixtySixty' => int 300 

我可以使用+ =來算,而是因爲有很多地區的我只算在同一區域。謝謝。

回答

0

更手動版本比卡洛斯的,但很直白:

$arr1 = YOUR_ARRAY_1; 
$arr2 = YOUR_ARRAY_2; 
$merged = $arr1; 

foreach($arr2 as $key => $val) { 
    if(array_key_exists($key, $merged)) { 
     $merged[$key] += $val; 
    } else { 
     $merged[$key] = $val; 
    } 
} 

這始於$arr1,並通過$arr2每個元素去。如果密鑰存在於$arr1中,則添加$arr2的值。如果不是,則創建一個新的數組元素。

相關問題