【问题标题】:How to get 7 highest value from the array如何从数组中获取 7 个最大值
【发布时间】:2020-03-30 09:46:23
【问题描述】:

我想从我的数组中获取 7 个最高值,但它应该正确排序

我有这个代码:

<?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;
?>

输出:

特丁吉:100,91,90,87,86,81,79

【问题讨论】:

  • 您的代码到底有什么问题?看来您确实已经获得了前 7 个值。
  • 定义“正确”。您可以以相反的顺序使用它,也可以不使用。演示:sandbox.onlinephpfunctions.com/code/…

标签: php arrays sorting arraylist


【解决方案1】:

您的代码几乎可以得到正确的输出,除了不能回显数组,您需要使用print_r() 或其他方法将数组转换为字符串。

但是为了让代码更紧凑,下面只使用了最少的(反正我能想到的)代码...

$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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多