Home>Article>Backend Development> How to sum one-dimensional arrays under php two-dimensional arrays
Steps: 1. Define an empty array to store the summation result of a one-dimensional array. The syntax is "$s=[];"; 2. Use "foreach($arr as $k=> $v){//Loop body}" loops through the outer elements of the two-dimensional array; 3. In the loop body, use is_array() to determine whether the outer element is an array type. If so, use array_sum() to calculate the Sum of elements of a dimensional array, syntax "if(is_array($v)){$s[]=array_sum($v);}".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
In PHP, you can use the foreach statement and combine it The is_array() and array_sum() functions are used to implement the sum of the next dimensional array of a two-dimensional array.
Implementation steps:
Step 1: Define an empty array to store the summation results of multiple one-dimensional arrays under a two-dimensional array
$sum=[];
Step 2. Use the foreach statement to loop through the outer array elements of the two-dimensional array
foreach($arr as $k => $v){ //循环体代码 }
Traverse the given $arr array, in each loop will assign the value of the current array to $v and the key name to $k.
Step 3: In the loop body, use the is_array() function to determine whether the outer element is an array type. If so, calculate the sum of the elements of the one-dimensional array
If so, use array_sum() to calculate the sum of the elements of the one-dimensional array
The array_sum() function is used to calculate the sum of all elements in the array
if(is_array($v)){ $sum[]=array_sum($v); }
The loop ends, then the $sum array contains the summation results of all one-dimensional arrays under the two-dimensional array
Complete implementation code:
$v){ if(is_array($v)){ $sum[]=array_sum($v); } } echo"二维数组下的一维数组的元素和:"; var_dump($sum); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to sum one-dimensional arrays under php two-dimensional arrays. For more information, please follow other related articles on the PHP Chinese website!