如何使下面的代码更优雅?目前我必须手动添加每个条件.有没有办法可以检查$ total_points的值是否位于数组$ ranking_list的连续项之间?
function ym_rank(){
$ranking_list = array(0, 400, 1000, 2500, 5000, 10000, 15000, 25000, 40000, 60000, 100000);
if($total_points >= $ranking_list[0] and $total_points < $ranking_list[1]){
return '<h2>Rank 0 </h2><br>';
}
elseif ($total_points >= $ranking_list[1] and $total_points < $ranking_list[2]){
return '<h2>Rank 1 </h2><br>';
}
.
.
.
so on
}
Run Code Online (Sandbox Code Playgroud)
我会用
for ($i = count($ranking_list) - 1; $i >= 0; $i--)
if ($total_points > $ranking_list[$i])
return 'Rank is' . $i . '<br>'.
Run Code Online (Sandbox Code Playgroud)
也许你应该稍微改变索引,但重点是,当你向后移动时,你不需要两个比较(and运算符).
| 归档时间: |
|
| 查看次数: |
103 次 |
| 最近记录: |