2014-01-26 58 views
0
Array1 ([a] => 1 [b] => 2 [c] => 7 [d] =>) 

Array2 ([a] => 2 [x] => 4 [y] => ) 

我試過這些添加兩個數組來獲得一個新的數組,其中匹配鍵值被添加。最終的陣列將是:PHP - 創建兩個簡單數組的總和

Array3 ([a] => 3 [b] => 2 [c] => 7 [d] => [x] => 4 [y] =>) 

我在看,但不能得到最終的陣列中所有鍵:

foreach($array1 as $key => $val) 
     { 
     $final_value = $val + $array2[$key]; 
     $final_array[] = array($key=>$final_value); 
     } 

是,我有,但不工作。

我也看了約拿的建議在:Merge 2 Arrays and Sum the Values (Numeric Keys)

回答

0

此經過兩個陣列,並比較它們彼此的關鍵。它可以通過檢查進行優化,使其不會與先前的值進行比較。

$array1 = array (
    'a' => 1, 
    'b' => 2, 
    'c' => 7, 
    'd' => // needs a value 
); 

$array2 = array (
    'a' => 2 
    'b' => 4 
    'c' => // needs a value 
); 

foreach ($array1 as $key1 => $value1) { 
    foreach ($array2 as $key2 => $value2) { 
     if ($key1 == $key2) { 
      $array3[$key1] = $value1 + $value2; 
     } 
    } 
} 
+0

的 '如果($ KEY1 == $ KEY2)' 將是真僅當元件相同的位置具有相同的密鑰名稱,否則將不會執行總計。 – FartMachine4U

2

在這裏,我們去:

$firstArray = array ('a' => 1, 'b' => 2, 'c' => 7, 'd' => 0); // d must have a value 
$secondArray = array ('a' => 2, 'x' => 4, 'y' => 0); // y must have a value 

$keys = array(); 
$result = array(); 

foreach($firstArray as $key => $value) { 
    $keys[] = $key; 
} 

foreach($secondArray as $key => $value) { 
    if(! in_array($key, $keys)) { 
     $keys[] = $key; 
    } 
} 

foreach($keys as $key) { 

    $a = 0; 
    $b = 0; 

    if(array_key_exists($key, $firstArray)) { 
     $a = $firstArray[$key]; 
    } 

    if(array_key_exists($key, $secondArray)) { 
     $b = $secondArray[$key]; 
    } 

    $result[$key] = $a + $b; 
} 

print_r($result); 

輸出:

陣列([α] => 3 [B] => 2 [C] => 7並[d] => 0 [X] => 4 [Y] => 0)

0

嘗試這個代碼

$Array3 = $Array1; 
foreach ($Array2 as $k => $v) { 
    $Array3[$k] = $Array3[$k] + $Array2[$k]; 
}