我如何在foreach php上使用foreach

时间:2012-08-11 12:34:53

标签: php curl foreach

大家好我有这个脚本,但显然我没有使用foreach,我想知道是否有我可以将这两个请求合并为一个

$url = "http://api.website.com/1.0/country?source=ballsche&programid=5380&campaignid=100000";
$ch = curl_init();
$timeout = 0;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$array = json_decode($rawdata,true);
foreach($array as $obj) {
    $country = $obj['country'];
    $countrycode = $obj['countryCode'];

}
foreach($countrycode as $did) {
    $wgurl = "http://api.website.com/1.0/city?source=ballsche&programid=5380&campaignid=100000&country-code=$did";
    $wgch = curl_init();
    $wgtimeout = 0;
    curl_setopt($wgch, CURLOPT_URL, $wgurl);
    curl_setopt($wgch, CURLOPT_HEADER, 0);
    curl_setopt($wgch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($wgch, CURLOPT_CONNECTTIMEOUT, $wgtimeout);
    $wgrawdata = curl_exec($wgch);
    curl_close($wgch);
    $wgarray = json_decode($wgrawdata,true);
}
foreach($wgarray as $wgobj) {
    $city = $wgobj['city'];
    $citycode = $wgobj['cityCode'];
    if($city){
        $sql = "INSERT INTO `pt_city` (city, citycode) VALUES ('$city', '$citycode')";
        database_queryModify($sql,$result);
        }else{
        echo "dint work";
    }

}

必须有一个简单的方法来做到这一点我猜测从数据创建另一个数组,但我不能正确我不断得到错误我尝试过这个和其他一些事情我的问题是我需要循环通过县代码和从代码中提出请求150个请求我需要循环通过以获取所有城市信息,并且对于每个请求我需要解码返回的json并将其插入我的城市表中

1 个答案:

答案 0 :(得分:1)

就像这样把foreach放在彼此里面

$url = "http://api.website.com/1.0/country?source=ballsche&programid=5380&campaignid=100000";
$ch = curl_init();
$timeout = 0;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$array = json_decode($rawdata,true);
foreach($array as $obj) {
    $country = $obj['country'];
    $countrycode = $obj['countryCode'];

    foreach($countrycode as $did) {
        $wgurl = "http://api.website.com/1.0/city?source=ballsche&programid=5380&campaignid=100000&country-code=$did";
        $wgch = curl_init();
        $wgtimeout = 0;
        curl_setopt($wgch, CURLOPT_URL, $wgurl);
        curl_setopt($wgch, CURLOPT_HEADER, 0);
        curl_setopt($wgch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($wgch, CURLOPT_CONNECTTIMEOUT, $wgtimeout);
        $wgrawdata = curl_exec($wgch);
        curl_close($wgch);
        $wgarray = json_decode($wgrawdata,true);

        foreach($wgarray as $wgobj) {
            $city = $wgobj['city'];
            $citycode = $wgobj['cityCode'];
            if($city){
                $sql = "INSERT INTO `pt_city` (city, citycode) VALUES ('$city', '$citycode')";
                database_queryModify($sql,$result);
            } else {
                echo "dint work";
            }
        }
    }   
}