如何找到数组中最高值≤特定值的键


How can I find the key of the highest value in an array ≤ a specific value?

我有一个数组,它将用户级别与该级别所需的最低点联系起来,如下所示:

$userLV = array(0 => 0, 1 => 400, 2 => 800);

关键是级别,值是该级别所需的最低分数。

如果用户有一定数量的$points,我需要通过从$userLV数组中找到对应于其最大值小于$points的密钥来找到他们的级别。

我怎样才能做到这一点?(示例数组是PHP,但使用JavaScript或任何语言的示例都会有所帮助。)

这里有一种方法(请注意,这取决于已经按升序排序的数组):

$level = 0;                           // start at 0
foreach ($userLV as $lv => $val) {    // loop through the levels
    if ($points >= $val) {
        $level = $lv;                 // reset the level as long as $points >= level value
    } else {
        break;                        // stop when it no longer is
    }
}

另一种选择是,如果你想继续为每400的倍数增加一个级别,那就是只使用数学。

$level = intval($points / 400);

Javascript 中的提案

function getLevel(points) {
    var level;
    [0, 400, 800].every(function (v, i) {
        if (points >= v) {
            level = i;
            return true;
        }
    });
    return level;
}
document.write([0, 200, 400, 600, 800, 1000].map(function (a) { return 'points: ' + a + ', level: ' + getLevel(a); }).join('<br>'));