2013-06-20 26 views
1

的下一個值我再次在這裏,學習PHP越來越多,但還是有我的方案的一些問題,我的大部分場景已經編程和解決沒有問題,但我發現一個問題,但要了解它,我需要先解釋它:重試數組循環內聲明在PHP,但與陣列

我有一個PHP腳本,可以由任何客戶端調用,其工作是接收請求,ping到從我手動定義的列表中進行代理,知道代理是否可用,如果可用,我繼續使用POST方法使用「curl」檢索響應。其中的邏輯是這樣的:

$proxyList = array('192.168.3.41:8013'=> 0, '192.168.3.41:8023'=>0, '192.168.3.41:8033'=>0); 
$errorCounter = 0; 

foreach ($proxyList as $key => $value){ 
if(!isUrlAvailable($key){ //It means it is NOT available so I count errors 
    $errorCounter++; 
} else { //It means it is AVAILABLE 
    $result = callThisProxy($key); 
} 
} 

功能"isUrlAvailable"使用$的fsockopen知道,如果代理可用。如果不是這樣,我就與CURL一個POST如前所述,該函數有callThisProxy()是這樣的:

$ch = curl_init($proxyUrl); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS,'xmlQuery='.$rawXml); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    $info = curl_exec ($ch); 
    if($isDebug){echo 'Info in the moment: '.$info.'<br/>';} 
    curl_close ($ch); 

但是,我們正在測試一些情況下,發生什麼事,如果我關閉代理的驗證之間的代理可用性和呼叫?我的意思是:

foreach ($proxyList as $key => $value){ 
if(!isUrlAvailable($key){ //It means it is NOT available so I count errors 
    $errorCounter++; 
} else { //It means it is AVAILABLE 
    $result = callThisProxy($key);//What happen if I kill the proxy when the result is being processed? 
} 
} 

我測試了它,當我這樣做,$結果之際,空字符串''。但問題是我失去了這個請求,我的目標是在下一個$key這是一個代理服務器重試它。所以,當我調用結果時,我一直在想着"do, while"。但不確定,如果沒問題,或者有更好的方法可以做到,那麼請在這個問題上尋求幫助。預先感謝您的時間,歡迎任何答案。謝謝。

+1

林困惑,你不調用代理後退出圈外,所以是不是要去嘗試下一個代理不管是什麼的返回值'callThisProxy($鍵)'是什麼? – immulatin

+0

它會嘗試下一個代理,但被關閉的代理的結果將爲空或空,而目標是始終爲其獲取結果。 –

回答

1

也許是這樣的:

$result = ""; 

while ($result == "") 
{ 
    foreach ($proxyList as $key => $value) 
    { 
     if (!isUrlAvailable($key)) 
     { 
      $errorCounter++; 
     } 
     else 
     { 
      $result = callThisProxy($key); 
     } 
    } 
} 

// Now check $result, which should contain the first successful callThisProxy() 
// result, or nothing if none of the keys worked. 
+0

非常適合,非常感謝! –

1

你可以只保留您仍然需要嘗試代理列表。當你遇到錯誤或得到有效的迴應時,你從代理列表中刪除代理嘗試。如果你沒有得到好的迴應,那麼將它保存在列表中,稍後重試。

$proxiesToTry = $proxyList; 
$i = 0; 

while (count($proxiesToTry) != 0) { 
    // reset to beginning of array 
    if($i >= count($proxiesToTry)) 
     $i = 0; 

    $proxy = $proxiesToTry[$i]; 

    if (!isUrlAvailable($proxy)) { //It means it is NOT available so I count errors 
     $errorCounter++; 
     unset($proxiesToTry[$i]); 
    } else { //It means it is AVAILABLE 
     $result = callThisProxy($proxy); 
     if($result != "") // If we got a response remove it from the array of proxies to try. 
      unset($proxiesToTry[$i]); 
    } 

    $i++; 
} 

注意:如果您從未從某個代理獲得有效響應,您將永遠不會擺脫此循環。