2012-08-12 104 views
0

当我需要检查array2是否有来自array1的某些值(随机生成)时,我遇到了这种情况。到目前为止,虽然我的
解决方法goto

redo : $id=mt_rand(0,count(array1)); 
foreach($array2 as $arr) 
{ 
    if($arr[0]==$id) goto redo; 
} 
//Some actions if randomly generated value from array1 wasn't found in array2 

但我真的不喜欢使用goto语句。我敢肯定有一些简单的解决办法做到不跳转,但我不能把它d:

+1

'do {$ id = mt_rand(...); $ contains =/*确定数组是否包含此id * /; } while($ contains);' – DCoder 2012-08-12 09:57:55

+0

按照建议使用合适的结构('do-while'),并且记住... **绝对不要**和**从不**使用'goto'运算符。这是一个笑话。对于真实情况:请查看[PHP手册](http:// it。)底部的[漫画](http://it.php.net/manual/en/images/0baa1b9fae6aec55bbb73037f3016001-xkcd-goto.png)。 php.net/manual/en/control-structures.goto.php) – 2012-08-12 10:15:18

+0

我看到了这张图片:P – 2012-08-12 10:42:50

回答

1

您可以使用数字参数与continuehttp://www.php.net/manual/en/control-structures.continue.php

while(true){ 
    $id = mt_rand(0,count(array1); 

    foreach($array2 as $arr) 
    // restart the outer while loop if $id found 
    if($arr[0] == $id) continue 2; 

    // $id not found in array, leave the while loop ... 
    break; 
}; 

// ... and do the action 
+1

感谢一群人工作正常。 – 2012-08-12 10:37:18

1

试试这个

$flag=true; 
do{ 
     $id=mt_rand(0,count(array1); 

     foreach($array2 as $arr) 
     if($arr[0] == $id) break; 

     // do it and set flag to false when you need to exit; 

    } while($flag); 
+0

如果在foreach之后只设置了$ flag = false,那么do-while循环将在两种情况下结束(如果匹配并且没有匹配)。然后在休息之前需要额外的标志,这将在foreach循环后检查是否匹配。这很麻烦,所以biziclop的代码在这里的工作方式更好 – 2012-08-12 10:42:11