2013-07-08 295 views
0

我正在尋找將兩個數組合併成一個數組,但我想保持鍵值相同並將它們的值累加成一個。PHP結合陣列鍵值?

使用PHP我正在尋找這樣的事情:

//inputs 
array(
    cat => 4, 
    dog => 3, 
    bug => 6 

); 

array(
    cat => 2, 
    dog => 5, 
    bug => 9, 
    ant => 3 

); 


//output 
array(
    cat => 6, 
    dog => 8, 
    bug => 15, 
    ant => 3 

); 
+0

你需要使用循環爲 –

回答

1

你可以通過將每個指標的添加陣列:(這裏假設你的第一陣列陣列1等)

<?php 
for ($i = 1; $i <= 4; $i ++) { 
    $array3[i] = $array1[i] + $array2[i]; 
} 
?> 

假設每個數組都有4個變量。

0
function func(&$value, $key) { 
    $value = (isset($value[1]) ? $value[0] + $value[1] : $value[0]); 
} 

$new_array = array_merge_recursive($array1, $array2); 
array_walk($new_array, 'func'); 
print_r($new_array); 
0
$final_array = array(); 

// u can iterate and get the name of the key while doing so, like so 
// add the first array 
foreach ($array1 as $prop=>$val) 
{ 
    $final_array[$prop]+=$val; 
} 


//add the second array 
foreach ($array2 as $prop=>$val) 
{ 
    $final_array[$prop]+=$val; 
} 

//result is in final_array 

//or more efficiently, just add the second to the first 
foreach ($array2 as $prop=>$val) 
{ 
    $array1[$prop]+=$val; 
}