两种不同的阵列

时间:2014-03-06 08:11:33

标签: php arrays

下面我有两个不同的数组:

Array ( [1] => 2 [2] => 3 [6] => 1 ) ; // array1 has 3 keys and 3 value 1=>2, 2=>3, 6=>1 
Array ( [1] => 2 [6] =>2 ) ;           // array2 has 2 keys and 2 value 1=>2, 6=>1 

我想与array1和array2相同的键可以同时使用SUM值:

Ex: array1 "[1]=>2" and array2 "[1]=>2" want to out put like that [1]=>4; [6]=>3

2 个答案:

答案 0 :(得分:2)

$result = array();
foreach ($array1 as $key => $value) {
    if (isset($array2[$key])) {
        $result[$key] = $value + $array2[$key];
    }
}

答案 1 :(得分:1)

foreach($array1 as $key => $value) {
    if(array_key_exists($key, $array2)) {
        $array1[$key] += array2[$key];
    }
}