In PHP development, it is often necessary to operate on arrays, and summation operations are also common. When we encounter two two-dimensional arrays that need to be summed, we can do it in the following ways.
Method 1: Use a loop to traverse each element and add and sum one by one.
The sample code is as follows:
<?php $array1 = array( array(1, 2, 3), array(4, 5, 6), ); $array2 = array( array(7, 8, 9), array(10, 11, 12), ); $rows = count($array1); $cols = count($array1[0]); $result = array(); for ($i = 0; $i < $rows; ++$i) { for ($j = 0; $j < $cols; ++$j) { $result[$i][$j] = $array1[$i][$j] + $array2[$i][$j]; } } print_r($result); ?>
Output result:
Array ( [0] => Array ( [0] => 8 [1] => 10 [2] => 12 ) [1] => Array ( [0] => 14 [1] => 16 [2] => 18 ) )
Method 2: Use the array_map() function to add and sum each element, which can reduce the amount of code .
The sample code is as follows:
<?php $array1 = array( array(1, 2, 3), array(4, 5, 6), ); $array2 = array( array(7, 8, 9), array(10, 11, 12), ); $result = array_map(function ($a, $b) { return array_map(function ($x, $y) { return $x + $y; }, $a, $b); }, $array1, $array2); print_r($result); ?>
Output result:
Array ( [0] => Array ( [0] => 8 [1] => 10 [2] => 12 ) [1] => Array ( [0] => 14 [1] => 16 [2] => 18 ) )
Method 3: Use the array_reduce() function to sum the two-dimensional array elements.
The sample code is as follows:
<?php $array1 = array( array(1, 2, 3), array(4, 5, 6), ); $array2 = array( array(7, 8, 9), array(10, 11, 12), ); $result = array_map(function ($a) { return array_reduce($a, function ($x, $y) { return $x + $y; }); }, array_map(null, $array1, $array2)); print_r($result); ?>
Output result:
Array ( [0] => 8 [1] => 10 [2] => 12 [3] => 14 [4] => 16 [5] => 18 )
The above three methods can be selected according to actual needs, and details such as formulas, functions, loops, etc. can be added as needed. Meet different computing needs.
The above is the detailed content of PHP sum of two two-dimensional arrays. For more information, please follow other related articles on the PHP Chinese website!