如何在php中计算数组的总和?

时间:2014-05-11 18:23:02

标签: php arrays

我有两个具有此结构的数组

array1 = Array(0=>Array(4, 7, 0, 11), 1=> Array(5,7,6,18));
array2 = Array(0=>Array(5,1,7,13), 1=>Array(9,1,6,16));

我尝试按照=> 4 + 5 = 9;

之类的元素计算此数组的总和
Array(0=>Array(9,8,7,24), 1=>Array(14, 8, 12, 34)); 

1 个答案:

答案 0 :(得分:1)

试试:

$array1 = [[4, 7, 0, 11], [5, 7, 6, 18]];
$array2 = [[5, 1, 7, 13], [9, 1, 6, 16]];

$output = array_map(function($a, $b){
    return array_map(function() {
        return array_sum(func_get_args());
    }, $a, $b);
}, $array1, $array2);

var_dump($output);

输出:

array (size=2)
  0 => 
    array (size=4)
      0 => int 9
      1 => int 8
      2 => int 7
      3 => int 24
  1 => 
    array (size=4)
      0 => int 14
      1 => int 8
      2 => int 12
      3 => int 34