我在尝试实现switch语句时遇到了一个问题。基本上,我试图让多个变量通过相同的switch语句,以防止自己重复不必要的代码。
我有变量$mon1
,$tue1
,$wed1
,$thu1
,$fri1
,我想通过单独的变量获取所有这五个变量下面的switch语句。我可以简单地为每个单独的变量添加一个新的switch语句,但似乎有更好的方法来处理它。
编辑:我为每个循环添加了一个,这很有效。我还有一个问题,那就是变量的分配。如果 - 例如 - $ mon1经过大小写“3”,那么$ mon1的值应该在switch语句的末尾为13。目前它没有分配该值。有什么指针吗?
$stress = array($mon1,$tue1,$wed1,$thu1,$fri1);
foreach($stress as $value){
switch ($value) {
case "1":
echo "This is 10";
$value = 10;
break;
case "2":
echo "This is 12";
$value = 12;
break;
case "3":
echo "This is 15";
$value = 15;
break;
case "4":
echo "This is 17";
$value = 17;
break;
case "5":
echo "This is 19";
$value = 19;
break;
}
}
答案 0 :(得分:1)
您可以为此目的使用一个功能:
function DecideStressByDay($value)
{
switch ($value) {
case "1":
$value = 10;
break;
case "2":
$value = 12;
break;
case "3":
$value = 15;
break;
case "4":
$value = 17;
break;
case "5":
$value = 19;
break;
}
return $value;
}
$mon1 = DecideStressByDay($mon1);
$tue1 = DecideStressByDay($tue1);
...
答案 1 :(得分:0)
这样的代码如何:
$stresses = array(
$mon1 => array(10, 12, 13, 17, 19),
$tue1 => array(10, 12, 15, 17, 19),
$wed1 => array(10, 12, 15, 17, 19),
$thu1 => array(10, 12, 15, 17, 19),
$fri1 => array(10, 12, 15, 17, 19)
);
/* change constants as per your situation */
foreach($stresses as $day => $stress ){
$switch ($day) {
case "1":
$value = $stress[0];
break;
case "2":
$value = $stress[1];
break;
case "3":
$value = $stress[2];
break;
case "4":
$value = $stress[3];
break;
case "5":
$value = $stress[4];
break;
}
/* do something with $value here or it'll get overwritten with every loop*/
}