求和不同的数组multidimention

时间:2018-01-17 04:51:43

标签: php multidimensional-array

任何人都可以帮助我进行总和2数组多维度,我尝试一些语法仍然无效。我使用2个数组而不是1个数组multidimention。

这是第一个数组

Array
(
    [0] => Array
        (
            [<-4] => 195
            [-4] => 327
            [-3] => 14
            [-2] => 10
            [-1] => 200
            [0] => 213
        )

    [1] => Array
        (
            [<-4] => 35
            [-4] => 0
            [-3] => 0
            [-2] => 0
            [-1] => 0
            [0] => 0
        )
)

这是另一个数组

Array
(
    [0] => Array
        (
            [<-4] => 0
            [-4] => 0
            [-3] => 0
            [-2] => 0
            [-1] => 0
            [0] => 0
        )

    [1] => Array
        (
            [<-4] => 0
            [-4] => 587
            [-3] => 17
            [-2] => 20
            [-1] => 359
            [0] => 1300
        )
 )

,结果与该数组的格式相同

1 个答案:

答案 0 :(得分:1)

<强>输入

    $array1 = array(
        array('<-4' => 195,'-4' => 327,'-3' => 14,'-2' => 10,'-1' => 200,0 => 213),
        array('<-4' => 35,'-4' => 0,'-3' => 0,'-2' => 0,'-1' => 0,0 => 0)
    );

    $array2 = array(
        array('<-4' => 0,'-4' => 0,'-3' => 0,'-2' => 0,'-1' => 0,0 => 0),
        array('<-4' => 0,'-4' => 587,'-3' => 17,'-2' => 20,'-1' => 359,'0' => 1300)
    );

<强>解决方案

    $new = array();
    for($i=0;$i<count($array1);$i++){
        foreach($array1[$i] as $key => $row){
            $new[$i][$key] = $array1[$i][$key]+$array2[$i][$key];
        }
    }

<强>输出

Array
(
    [0] => Array
        (
            [<-4] => 195
            [-4] => 327
            [-3] => 14
            [-2] => 10
            [-1] => 200
            [0] => 213
        )

    [1] => Array
        (
            [<-4] => 35
            [-4] => 587
            [-3] => 17
            [-2] => 20
            [-1] => 359
            [0] => 1300
        )

)