dongnaizao8039 2016-03-23 12:57
浏览 18
已采纳

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

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.)

  • 写回答

2条回答 默认 最新

  • duanluanhui8348 2016-03-23 13:26
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部