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

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