e.g。如果我通过$total = 2
那么它应该先计算总和
两个阵列
sub1 + sub2
**这是我的代码**
<?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);
?>
答案 0 :(得分:3)
试
<?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;
输出就像:
Array
(
[sub1] => 30
[sub2] => 19
[sub3] => 56
[sub4] => 47
[sub5] => 6
)
sum of 2 array is : 49
应该做的伎俩。希望它有所帮助:)
答案 1 :(得分:0)
只需你可以像这样使用循环
$sum=0;
for($i=0;$i<$total;$i++){
$sum+=$result[$i];
}