我最近创建了一个if语句脚本,它根据数字代表的内容设置变量。在意识到脚本相当长并且最有可能以更有效的方式完成之后,我在互联网上查看并没有找到太多结果。这是我的剧本
if ($row[position] == 1){
$variable = 1;
} elseif ($row[position] == 2){
$variable = 1;
} elseif ($row[position] == 3){
$variable = 2;
} elseif ($row[position] == 4){
$variable = 2;
} elseif ($row[position] == 5){
$variable = 3;
} elseif ($row[position] == 6){
$variable = 3;
} elseif ($row[position] == 7){
$variable = 4;
} elseif ($row[position] == 8){
$variable = 4;
} elseif ($row[position] == 9){
$variable = 5;
} elseif ($row[position] == 10){
$variable = 5;
} elseif ($row[position] == 11){
$variable = 6;
} elseif ($row[position] == 12){
$variable = 6;
} elseif ($row[position] == 13){
$variable = 7;
} elseif ($row[position] == 14){
$variable = 7;
} elseif ($row[position] == 15){
$variable = 8;
} elseif ($row[position] == 16){
$variable = 8;
}
如您所见,这是一个非常基本的模式。
1 = 1
2 = 1
3 = 2
4 = 2
5 = 3
6 = 3
依旧......
我不是在寻找要完成的工作,因为它可能很多,但我只是想知道我应该怎么做。感谢。
答案 0 :(得分:6)
这应该对你有用
<?php
$row["position"] = 4; //example
//if (($row["position"] >= 1) && ($row["position"] <= 16) ) -> if you only want to set the variable if it's between 1 and 16 or something else use this if statement
$variable = ceil($row["position"] / 2);
echo $variable;
?>
答案 1 :(得分:1)
除了Rizier123的答案,你可以使用round()
和PHP_ROUND_HALF_UP模式: -
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
foreach($numbers as $number){
echo round($number / 2, 0, PHP_ROUND_HALF_UP) . "\n";
}
答案 2 :(得分:1)
你可以使用%(mod)运算符和除(/)来做技巧
这是诀窍,
1.使位置均匀。即如果位置已经平衡,则另外加1以使其均匀。
2.将位置除以2得到var $ variable的期望值
$pos = $row[position];
if ($pos % 2 == 1) //Check for odd
{
$pos = $pos + 1; //odd+1 =even (converting odd as even)
}
$variable = $pos/2;
示例:
$ row [position] = 3 =&gt; $ pos是奇数,所以即使是3 + 1也是如此4 =&gt;变量= 4/2 =&gt; 2
$ row [position] = 4 =&gt; $ pos甚至是这样离开,因为它=&gt;变量= 4/2 =&gt; 2
$ row [position] = 5 =&gt; $ pos是奇数,所以即使是5 + 1也是如此6 =&gt;变量= 6/2 =&gt; 3