在 switch 语句中选择随机代码

Choose random code within switch statement

我在多个案例中使用了 switch 语句。

When one of the cases is chosen, how can I randomly choose a block of code within that case, but without using a nested switch statement?

例如:

switch ($choose_case){

case 1:
//some code
break;

case 2:
//some code
break;

case 3:
(random block of code #1)
(random block of code #2)
=randomly choose #1 or #2
break;

}

不了解你,但我会这样做。

switch ($choose_case){

case 1:
//some code
break;

case 2:
//some code
break;

case 3:
$var = rand(1,2);
  if($var == 1)
  {
     //case 1 
  }
  else
  {
     //case 2
  }

break;

}

最好的方法是给 $choose_value 一个介于 1 和 2 之间的随机数,然后用新值再次调用包含开关的函数。所以,在你的情况下:

function do_something($choose_case){

 switch ($choose_case){

   case 1:
   //some code
   break;

   case 2:
   //some code
   break;

   case 3:
   $choose_case = floor(rand(1.5,2.5));
   do_something($choose_case);
   break;

}