Turning curl requests inside nested foreach loops into a PHP multi-curl

26 views Asked by At

I am making multiple api requests using PHP curl. The first request returns (among other things) a series of requirement IDs which are then used in the api query string to request operation data related to each requirement. I then need to return a new json feed of the results. I wrote the following which does work but is very very slow as it makes all the requests to the second api in sequence rather than asynchronously. I want to use curl-multi to do this but am tripping up on all the foreach loops. Any help would be very much appreciated.

'''

// Call API Feed
function curlfunc($curlurl) {
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $curlurl,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "Accept: application/json",
        "Accept-Encoding: gzip, deflate"
    ),
));
$curlresponse = curl_exec($curl);
curl_close($curl);
return $curlresponse;
}

//Get query string
$query1 = $_GET['query1'];

if (isset($query1)) {
    $curlurl = 'https://api.url.com?query1='.$query1;
    $requir = json_decode(curlfunc($curlurl));
    if ($requir) {
        foreach ($requir as $req) {
            foreach ($req->SubGroups as $subgroup ) {
                foreach ($subgroup->SubGroups as $subsubgroup) {
                    $groupdesc = $subsubgroup->Group_Description;
                    foreach ($subsubgroup->Requirements as $requirement) {
                        $reqid = $requirement->Requirement_ID;
                        $curlurl = 'https://api.url2.com?query2=' .$reqid;
                        $operations = json_decode(curlfunc($curlurl));
                        $duration = 0;
                        foreach($operations as $operation) {
                            $desc = $operation->OperationDescription;
                            $loadhours = $operation->LoadHours;
                            $duration+= $loadhours;
                        }
                        $output[] = array('Group_Description'=>$groupdesc, array('Requirement_ID'=>$requirement->Requirement_ID, 'OperationDescription'=>$desc, 'LoadHours'=>$duration));
                    }
                }
            }
        }
    }
echo json_encode($output);
}

'''

0

There are 0 answers