我问这个问题要知道,还有其他最好的方法可以在最少的行中编写这个逻辑吗?
这是我的代码,包含很多if
和elseif
条件:
if ($emission <= 100 ) {
$cssClass = "emission_a";
} elseif ($emission > 101 && $emission <= 120 ){
$cssClass = "emission_b";
} elseif ($emission >= 121 && $emission <= 150 ){
$cssClass = "emission_c";
} elseif ($emission >= 151 && $emission <= 165 ){
$cssClass = "emission_d";
} elseif ($emission >= 166 && $emission <= 185 ){
$cssClass = "emission_e";
} elseif ($emission >= 186 && $emission <= 125 ){
$cssClass = "emission_f";
} elseif ($emission >= 226){
$cssClass = "emission_g";
}
希望有人可以帮助我。 谢谢。
答案 0 :(得分:4)
如果简化了条件,你可以省去一些字符,但是你需要相同数量的if / elseif语句
Array
(
[0] => one
[1] => two
[2] => group1,three
[3] => group1,four
[4] => group2,five
[5] => group3,six
)
或者你尝试使用像这样的映射数组
<?php
if ($emission <= 100 ) {
$cssClass = "emission_a";
} elseif ($emission <= 120 ) {
$cssClass = "emission_b";
} elseif ($emission <= 150 ) {
$cssClass = "emission_c";
} elseif ($emission <= 165 ) {
$cssClass = "emission_d";
} elseif ($emission <= 185 ) {
$cssClass = "emission_e";
} else {
$cssClass = "emission_g";
}
// this one makes no sense, maybe a typo?
// } elseif ($emission >= 186 && $emission <= 125 ){