简体   繁体   中英

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

I have an array that relates a user level to minimum points required for that level, like this:

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

The key is the level and the value is the minimum points required for that level.

If a user has a certain number of $points , I need to find their level by finding the key from the $userLV array that corresponds to its greatest value less than $points .

How can I achieve this? (The example array is PHP, but an example in JavaScript or any language will be helpful.)

Here is one way to do it (please note that this depends on the array already being sorted in ascending order):

$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
    }
}

Another option, if you want to continue to increment level for every multiple of 400 is to just use math.

$level = intval($points / 400);

A proposal in 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>'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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