[英]How do I count the sum of specified sum in $total
eg if I pass $total = 2
then it should calculate the sum of first two arrays. 例如,如果我传递
$total = 2
那么它应该计算前两个数组的和。
sub1 + sub2
**HERE IS MY CODE ** **这是我的代码**
<?php
$num = 2;
$array = array();
$total = 2;
for($x=1;$x<=$num;$x++)
{
$result = array('sub1'=>rand(1,100),
'sub2'=>rand(1,100),
'sub3'=>rand(1,100),
'sub4'=>rand(1,100),
'sub5'=>rand(1,100));
$array[] = $result;
}
echo '<pre>'; print_r($array);
?>
try 尝试
<?php
$array = array();
$total = 2;
$result = array('sub1'=>rand(1,100),
'sub2'=>rand(1,100),
'sub3'=>rand(1,100),
'sub4'=>rand(1,100),
'sub5'=>rand(1,100));
$temp_array = array_slice($result, 0, $total);
$sum = array_sum($temp_array);
print_r($result);
echo "sum of $total array is : ".$sum;
Output would be like : 输出如下:
Array
(
[sub1] => 30
[sub2] => 19
[sub3] => 56
[sub4] => 47
[sub5] => 6
)
sum of 2 array is : 49
https://eval.in/539097 https://eval.in/539097
should do the trick. 应该可以。 hope it helps :)
希望能帮助到你 :)
simply you can use for loop like this 只需使用这样的for循环
$sum=0;
for($i=0;$i<$total;$i++){
$sum+=$result[$i];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.