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