Php 为什么我的函数发送多个cURL请求失败?

Php 为什么我的函数发送多个cURL请求失败?,php,curl,Php,Curl,我有一个函数historicalBootstrap,我想用它将三个不同的数据集放入一个页面: $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" ); fun

我有一个函数historicalBootstrap,我想用它将三个不同的数据集放入一个页面:

$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);
$years=数组(
日期('Y-m-d',标准时间('1年前')。“.json”,
日期('Y-m-d',标准时间('2年前')。“.json”,
日期('Y-m-d',标准时间('3年前')。“.json”
);
函数历史引导($years,$id){
对于($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);
卷曲关闭($i);
$i=json_解码($jsonHistoricalRates);
echo'.$i.'historical='.json_encode($historicalRates)。;';
}   
}
历史引导($years,$appId);
我似乎可以使用这种方法发出一个请求,例如,在功能块之外。为什么当我将这种方法抽象为历史引导函数时它失败了?我希望有三个(_0=…,_1=…,_2=…)引导脚本


多谢各位

您正在使用
$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>';
    }   
}

现在,如果您在函数中使用了4年,则不需要修改此代码。

为什么要使用它而不是foreach循环?如果出现奇数,您的键可能没有数字索引,或者它跳过了一个数字,那么脚本将抛出一个错误。
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>';
    }   
}