2014-09-04 75 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年后也不会要求修改这个功能码。