bhttoan
bhttoan

Reputation: 2736

Looping through an API with offsets

I am using an API which is limited to returning 100 items in a single request - they have implemented offsets which should then allow looping through multiple requests but I can't get my head around how to combine the two.

At the moment I am using this which returns 100 items and gives me all the data etc I need but there are around 2,000 items in total and I need to loop them all:

try {
    $all = RestClient::all(array("limit" => 100));
    foreach($all as $entry){
        //do something
}

catch(Exception $e) {
    print $e;
}

The documentation shows an example of how to use the offset:

$resList = RestClient::all(array('limit'=>100));    
echo $resList->nextOffset();    
if($resList->nextOffset()) {     
   $resList = RestClient::all(array("limit" => 100, "offset" => $resList->nextOffset()));    
   echo $resList->nextOffset();
}

The example doesn't show any looping so where does my loop go? Do I need multiple loops?

If I add a loop after the first $resList then it will loop through those 100 but no more though I assume if I add it in the if then it will never be met as the offset will never be defined?

How can I use the offset to loop through all the items - in effect, combine both sets of code?

Upvotes: 0

Views: 1269

Answers (1)

Santa's helper
Santa's helper

Reputation: 996

$offset = 0;
while (true) {
    $resList = RestClient::all(array('limit'=>100, , "offset" => $offset));

    foreach($resList as $entry) {
        // do something
    }
    if (!$resList->nextOffset()) {
        brake;
    }
    $offset = $resList->nextOffset();
}

Upvotes: 1

Related Questions