使用php从列表中添加四个最小的元素


Adding foursmallest elements from alist using php

我想从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; 

您需要使用sortarray_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