2012-08-12 105 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