我想添加一个数组键和值与另一个数组值

时间:2016-10-18 14:28:34

标签: php arrays

我想添加一个数组键和值与另一个数组的值。

如果我有如下数组:

Array ( [6] => 12 [8] => 9 [10] => 11 )

Array ( [6] => 70 [8] => 10 [9] => 35 [10] => 25 [11] => 25 [12] => 2 )

例如(6 => 12,当处理结果为70 + 2时)

这是上面两个数组的预期输出:

array ([0] => 72 [1] => 45 [2] => 50 )

提前致谢

2 个答案:

答案 0 :(得分:0)

使用以下简单解决方案:

$arr1 = [6 => 12, 8 => 9 , 10 => 11];
$arr2 = [6 => 70, 8 => 10, 9 => 35, 10 => 25, 11 => 25, 12 => 2];

$result = [];
foreach ($arr1 as $k => $v) {
    if (isset($arr2[$k]) && isset($arr2[$v])) {
        $result[] = $arr2[$k] + $arr2[$v];
    }
}

print_r($result);

输出:

Array
(
    [0] => 72
    [1] => 45
    [2] => 50
)

答案 1 :(得分:0)

$array1 = Array ( 6 => 12, 8 => 9, 10 => 11 );

$array2 = Array ( 6 => 70, 8 => 10, 9 => 35, 10 => 25, 11 => 25, 12 => 2 );

$newarray = array();
foreach ($array1 as $key => $item) {
    $newarray[] = $array2[$item] + $array2[$key];
}

var_dump($newarray);