2014-09-04 70 views
0

我有這個功能,historicalBootstrap,我想用把三個不同的數據集到一個頁面:爲什麼我的函數發送多個cURL請求失敗?

$years = array(
     date('Y-m-d', strtotime('1 year ago')). ".json", 
     date('Y-m-d', strtotime('2 years ago')). ".json", 
     date('Y-m-d', strtotime('3 years ago')). ".json"  
    ); 

function historicalBootstrap($years, $id){ 

    for($i = 0; $i < 3; $i++){ 

     $date = $years[$i]; 

     $i = curl_init("http://openexchangerates.org/api/historical/{$date}?app_id={$id}"); 
     curl_setopt($i, CURLOPT_RETURNTRANSFER, 1); 

     $jsonHistoricalRates = curl_exec($i); 
     curl_close($i); 

     $i = json_decode($jsonHistoricalRates); 
     echo '<script>_'. $i . 'historical = '. json_encode($historicalRates) . ' ; ' . '</script>'; 

    } 
} 

historicalBootstrap($years, $appId); 

看來我可以用這種方法來使一個請求,例如在功能塊之外。爲什麼當我將這種方法抽象到HistoricalBootstrap函數中時會失敗?我期待三個(_0 = ...,_1 = ...,_2 = ...)自舉腳本。

謝謝。

+0

爲什麼使用它而不是foreach循環?在奇怪的情況下,你的密鑰可能沒有數字索引,或者它跳過一個數字,你的腳本會拋出一個錯誤。 – 2014-09-04 20:05:17

回答

1

您正在使用$i來控制您的for循環,並且還包含curl句柄並還包含json解碼結果。

您也正在解碼返回的json,然後直接對其進行編碼,而不是必需的。

嘗試將其更改爲

function historicalBootstrap($years, $id){ 

    for($i = 0; $i < 3; $i++){ 
     $date = $years[$i]; 
     $ch = curl_init("http://openexchangerates.org/api/historical/{$date}?app_id={$id}"); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     $jsonHistoricalRates = curl_exec($ch); 
     curl_close($ch); 
     echo '<script>_'. $i . 'historical = '. $jsonHistoricalRates . ';' . '</script>'; 
    } 
} 

你也可以讓這個更靈活的使用foreach()代替for

function historicalBootstrap($years, $id){ 
    foreach ($years as $i => $year) { 
     $ch = curl_init("http://openexchangerates.org/api/historical/{$year}?app_id={$id}"); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     $jsonHistoricalRates = curl_exec($ch); 
     curl_close($ch); 
     echo '<script>_'. $i . 'historical = '. $jsonHistoricalRates . ';' . '</script>'; 
    } 
} 

現在,如果你超過了4年後也不會要求修改這個功能碼。