dongnaizao8039 2016-03-23 20: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 21: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条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作