我有一个将用户级别与该级别所需的最低点相关联的数组,如下所示:
$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);