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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动