简体   繁体   English

如何从数组中获取 7 个最大值

[英]How to get 7 highest value from the array

I want to get 7 highes values from my array, but it should be sorted properly我想从我的数组中获得 7 个最高值,但应该正确排序

I have this code:我有这个代码:

<?php    
$nilai = array(72,65,73,78,75,74,90,81,87,65,55,69,72,78,79,91,100,40,67,77,86);
$jumlah = 0;
for ($i = 0; $i <= count($nilai)-1; $i++)
{
    $jumlah += $nilai[$i];
}
$rata = $jumlah/count($nilai);
$max = $nilai[0];
for ($i = 0; $i <= count($nilai)-1; $i++)
{
    if ($nilai[$i] > $max)
    {
        $max = $nilai[$i];
    }
    rsort($nilai);
    $top7 = array_reverse(array_slice($nilai, 0, 7));
}
echo "Rata-Rata : ".$rata;
echo "<br>";
echo "Tertinggi : ".$top7;
?>

Output :输出 :

Tertinggi : 100,91,90,87,86,81,79 Tertinggi : 100,91,90,87,86,81,79

Your code almost get the right output, except you cannot echo an array, you need to use print_r() or some other method to convert the array to a string.您的代码几乎得到了正确的输出,除了您无法回显数组之外,您需要使用print_r()或其他一些方法将数组转换为字符串。

But to make the code more compact, the following uses just the minimum (I can think of anyway) code...但是为了使代码更紧凑,以下仅使用了最少的(无论如何我都能想到)代码...

$nilai = array(72,65,73,78,75,74,90,81,87,65,55,69,72,78,79,91,100,40,67,77,86);

// Average
$jumlah = array_sum($nilai);
$rata = $jumlah / count ( $nilai );
echo "Rata-Rata : ".$rata;
echo "<br>";

// Top 7
rsort($nilai);
$top7 = array_slice($nilai, 0, 7 );

echo "Tertinggi : ";
print_r($top7);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM