目前,我有36个正在改组的变量(对于一个非常具体的WP原因)。无论如何,一旦变量洗牌,我试图将它们与名称相匹配。因此,如果$ numbers [0]等于1,则应该打印“John”。我目前正在使用36个switch case语句来实现这一点,我知道这是超级低效的。所以我想知道是否有更聪明的方法来做到这一点?
这是我的代码(例如,我只显示3个变量和3个开关案例):
$numbers = range(1, 3);shuffle($numbers);
switch ($numbers[0]){
case "1":
echo $numbers[0] . " is John";
break;
case "2":
echo $numbers[0] . " is Jane";
break;
case "3":
echo $numbers[0] . " is Mirza";
break;
}
switch ($numbers[1]){
case "1":
echo $numbers[1] . " is John";
break;
case "2":
echo $numbers[1] . " is Jane";
break;
case "3":
echo $numbers[1] . " is Mirza";
break;
}
switch ($numbers[2]){
case "1":
echo $numbers[2] . " is John";
break;
case "2":
echo $numbers[2] . " is Jane";
break;
case "3":
echo $numbers[2] . " is Mirza";
break;
}
答案 0 :(得分:1)
首先将所有名称写入数组:
$names = array(
0 => 'John',
1 => 'Jane',
2 => 'Mirza'
);
之后使用foreach:
foreach($numbers as $number){
echo $names[$number];
}
非常简单,祝你好运! :)
答案 1 :(得分:1)
不太确定你的目标是什么;你的例子有点抽象。但是你可以做两件事:
// loop
foreach ($numbers as $n) {
switch($n) { ... }
}
然后,如果比较总是针对静态列表,那么这样做是为了避免使用switch语句:
$compare = array("", "John", "Jane", "Mirza");
// loop
print $compare[n];
答案 2 :(得分:0)
这样的事情可以节省你的一天:
$theCase = array ( " is John", " is Jane", " is Mirza");
$numbers = range(1, 3);shuffle($numbers);
for ($i=0;$i<3;$i++)
echo $numbers[$i] . $theCase[$numbers[$i]];