从数组 PHP 中获取 3 个最低值


Get 3 lowest values from an array, PHP

所以我知道min()可以从数组中得到最低值,但是我需要数组中的 3 个最低值。

假设我的数组名为 $myArray

我在数组中使用了asort($myArray),然后print_r($myArray)输出以下内容:

Array (
    [137] => 4.90416668118
    [135] => 7.1203544474
    [18] => 7.2476262434
    [81] => 8.37903400152
    [33] => 9.1074567001
    [4] => 9.90788482793
    [138] => 10.2493339987
    [5] => 11.6024401676
    [63]...and so on until
    [124] => 8727.73285117
    [153] => 8727.73285117
    [117] => 8727.73285117
)

如果我需要,如何获得 3 个第一个值或 X 个第一个值......

我应该指定:丢失钥匙是否可以做到这一点?

asort($yourarray, SORT_NUMERIC);
print_r(array_slice($yourarray, 0, 3, true));

http://www.php.net/manual/en/function.asort.php

http://www.php.net/manual/en/function.array-slice.php

就像 Brad 的回答一样,但使用 ksort 来保留关联数组中的键:

ksort( $arr );
print_r( array_slice( $arr, 0, 3, true ) );