我想从10个科目中添加表现最好的5个科目的总和
$scores=(1,2,1,2,3,5,6,8,9,7)
学生成绩如上表
我想从列表$agg ie(1,1,2,2,3)
中取出sum five small elements
我的答案应该是9 in best five
/* fist sort the fist five small numbers using following script */
$scores=array(1,2,1,2,3,5,6,8,9,7); // array list
$sum_five_small_elements = 0;
sort($scores);
for($x = 0; $x < 5 ; $x++) {
/* now sum all five small elements */
$sum_five_small_elements += $scores[$x];
}
echo $sum_five_small_elements;
您需要使用sort
和array_slice
以及array_sum
作为
$scores = array(1,2,1,2,3,5,6,8,9,7);
sort($scores);
print_r(array_sum(array_slice($scores, 0,5)));//9
首先,我使用sort
对值进行排序,这将从lowest to highest
对数组进行排序
Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 2 [4] => 3 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 )
之后,我使用array_slice
将数组切成两部分,这将得到
Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 2 [4] => 3 )
最后使用array_sum
它将对数组求和结果为
9