2014-07-07 39 views
0

如果出现任何错误,我将使用goto,并且它会从顶部重新开始。把goto换成while循环?

我也不能在函数中使用goto来跳出函数。

我知道goto是坏的,但while循环如何适合我的代码?

例如:

$ch = curl_init(); 

retry: 

$result = curlPost($ch, "home.php", http_build_query($arg)); 

if (strpos($postResult, "Welcome") !== false) { 
    sleep(10); 
    goto retry; 
} 

$sql = "SELECT * FROM data"; 
$q = mysql_query($sql) or die(mysql_error()); 

while($row = mysql_fetch_assoc($q)) { 
    $name['something'] = $row['name']; 
    submitData($ch,$name); 
} 


function submitData($ch,$name) { 

    $result2 = curlPost($ch, "submit.php", http_build_query($name)); 

    if (strpos($postResult, "Website close") !== false) { 
     sleep(10); 
     goto retry; //goto wouldnt work. 
    } 

    // do something here 
} 
+0

它会适合比goto更好。 – Phantom

+0

@Phantom在我的示例中使用while循环回答问题。 – user1246800

回答

1

基本上,你就会有这样的事情:

$success = false; 
while(!$success) { 
    // do stuff here 
    // psuedocode follows: 
    if failure { 
     continue; // skip remainder of `while` and retry 
    } 
    if complete { 
     $success = true; // loop will end 
     // or "break;" to exit loop immediately 
    } 
} 

要知道,如果你的“如果失败”本身就是一个循环中,你将需要continue 2; 。或者,如果您处于嵌套循环中,则可以使用continue 3;等。

+0

谢谢,这很有帮助。我想我已经设法用'while'循环替换我的例子..你能检查这是否正确吗? http://pastebin.com/U5Bpkt7A – user1246800

+0

差不多。只是'错误'错字'flase',你不需要'$ tryAgain'。 'submitData'逻辑重试也是倒退。 [试试这个](http://pastebin.com/yGS8Dmgv) –