Home > Enterprise >  Foreach loop inside while loop - it never ends
Foreach loop inside while loop - it never ends

Time:06-24

So, I have one curl API call which works fine when I do foreach outside the while loop. Once I move the foreach inside (because I need the values inside) it becomes an infinity loop.

This is the setup

$query = "SELECT id, vote FROM `administrators` WHERE type = 'approved'";
$result = $DB->query($query);

$offset = 0;
$length = 5000;
    
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  
                    
do {
  curl_setopt($ch, CURLOPT_URL, "https://api.gov/data?api_key=xxxxxxxxxx&start=1960&sort[0][direction]=desc&offset=$offset&length=$length");
    
  $jsonData = curl_exec($ch);
  $response = json_decode($jsonData);
                
  foreach($response->response->data as $finalData){
      $allData[] = $finalData; 
  }
    
  $offset  = count($response->response->data);
    
} while ( count($response->response->data) > 0 );
    
curl_close($ch); 

while($row = $DB->fetch_object($result)) {

   foreach ( $allData as $key => $finalData1 ) {
         
        // rest of the code
   }
}

Once I run the page it goes infinity or until my browser crash. If I move foreach ( $allData as $key => $finalData1 ) { } outside the while(){} there is no such problem.

Any ideas on what can be the problem here?

UPDATE: // rest of the code

$dataValue = str_replace(array("--","(s)","NA"),"NULL",$finalData1->value);
if($frequency == "dayly") {
    if($dataValue) {
        $query = "UPDATE table SET $data_field = $dataValue WHERE year = $finalData1->period AND id = $row->id LIMIT 1";
    }
}

if(isset($query))
$DB->query($query);
unset($query);

CodePudding user response:

One of the issues could be that where

// rest of the code

is, you have duplicate variable names, thus overriding current positions in arrays and loops.

However, you should change your approach to something like

$rows = Array();
while($row = $DB->fetch_object($result)) $rows[] = $row;

foreach ($rows as $row) {
  foreach ($allData as $key => $finalData1) {
    // rest of the code
  }
}

That way you can read resultset from database faster and free it before you continue.

  •  Tags:  
  • php
  • Related