2012-08-12 2 views
0

array2에 array1에서 임의의 값 (임의로 생성 된 값)이 있는지 확인해야 할 때가 왔습니다. 지금까지의
고토 해결 방법

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 

생각하지만 난 정말 고토를 사용하지 않으려는 것입니다.

+1

do {$ id = mt_rand (...); $ contains =/* 배열에이 id가 들어 있는지 판단 * /; } 012 ($ contains);' – DCoder

+0

적절한 구조 (do-while)를 제안대로 사용하고 기억하십시오 ... ** 절대로 절대로 ** 결코 ** 고토 ** 연산자를 사용하지 마십시오. 그것은 농담. 실제의 경우 : [PHP 매뉴얼] 하단의 [만화] (http://it.php.net/manual/en/images/0baa1b9fae6aec55bbb73037f3016001-xkcd-goto.png) (http : // it. php.net/manual/en/control-structures.goto.php) –

+0

그 그림을 보았습니다 : P –

답변

1

당신은 continue와 숫자 매개 변수를 사용할 수 있습니다 : http://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

감사합니다. –

1

이 시도 나는 D가 고토없이이 작업을 수행하는 몇 가지 간단한 솔루션입니다하지만 난 그냥 생각할 수 없다 확신 해요

$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의 코드가 더 잘 작동합니다. –