PHP 数组总和
PHP 有一个内置函数 array_sum()
,用于对数组的所有值求和。
此函数采用一个参数,即要对值求和的数组。它只需要一个一维的关联数组作为参数。
array_sum()
将所有值相加后返回一个整数或浮点值;如果数组为空,它将返回 0
。
本教程演示了 array_sum()
的用法以及如何对多维数组的值求和。
在 PHP 中使用 array_sum()
函数对数组的值求和
array_sum()
只能用于一维和关联数组。
// Sum of the values of a one dimensional array.
$sum_array=array(10,20,30,40,50);
echo "Sum of the one-dimensional array is: "
echo array_sum($sum_array);
echo "<br>";
// Sum of the values of one associative array.
$sum_array=array("val1"=>10.5,"val2"=>20.5,"val3"=>30.5,"val4"=>40.5,"val5"=>50.5);
echo "Sum of the associative array is: "
echo array_sum($sum_array);
上面的代码将对相应数组的值求和。在关联数组的情况下,array_sum()
只会对值求和,而不是对键求和。
输出:
Sum of the one-dimensional array is: 150
Sum of the associative array is: 152.5
在 PHP 中计算多维数组的所有值的总和
我们可以对多维数组使用 foreach 循环来计算所有值的总和。
<?php
$multi_array = [
["val1"=>10,"val2"=>20,"val3"=>30,"val4"=>40,"val5"=>50],
["val1"=>10.5,"val2"=>20.5,"val3"=>30.5,"val4"=>40.5,"val5"=>50.5],
["val1"=>60,"val2"=>70,"val3"=>80,"val4"=>90,"val5"=>100],
["val1"=>60.5,"val2"=>70.5,"val3"=>80.5,"val4"=>90.5,"val5"=>100.5]
];
$sum_array = array();
foreach ($multi_array as $k=>$sub_array) {
foreach ($sub_array as $id=>$val) {
$sum_array[$id]+=$val;
}
}
print "Sum of full Array : ".array_sum($sum_array)."<br/>";
?>
上面的代码将首先计算多维数组的列总和,并返回一个包含列值总和的数组。然后我们使用 sum_array()
函数。
见输出:
Sum of full Array : 1105
使用 PHP 中的 sum_array()
函数计算多维数组的特定列的总和
我们知道,sum_array()
不能返回多维数组的总和,但它可以与另一个内置函数 array_column()
一起使用。
array_column()
将返回一个数组,其中包含键和值以及给定多维数组中的一列。它需要两个强制参数,数组和列或索引键。
<?php
$multi_array = [
["val1"=>10,"val2"=>20,"val3"=>30,"val4"=>40,"val5"=>50],
["val1"=>10.5,"val2"=>20.5,"val3"=>30.5,"val4"=>40.5,"val5"=>50.5],
["val1"=>60,"val2"=>70,"val3"=>80,"val4"=>90,"val5"=>100],
["val1"=>60.5,"val2"=>70.5,"val3"=>80.5,"val4"=>90.5,"val5"=>100.5]
];
$sum_val1 = array_sum(array_column($multi_array, "val1"));
print "Sum of column val1 : ".$sum_val1."<br/>";
$sum_val2 = array_sum(array_column($multi_array, "val2"));
print "Sum of column val2 : ".$sum_val2."<br/>";
$sum_val3 = array_sum(array_column($multi_array, "val3"));
print "Sum of column val3 : ".$sum_val3."<br/>";
$sum_val4 = array_sum(array_column($multi_array, "val4"));
print "Sum of column val4 : ".$sum_val4."<br/>";
$sum_val5 = array_sum(array_column($multi_array, "val5"));
print "Sum of column val5 : ".$sum_val5."<br/>";
?>
输出:
Sum of column val1 : 141
Sum of column val2 : 181
Sum of column val3 : 221
Sum of column val4 : 261
Sum of column val5 : 301
我们还可以使用带有 array_sum
和 array_column()
函数的循环来计算多维数组的所有值的总和。
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook