PHP API offset Pagination

Viewed 470

I have the following code but I am not sure how to loop and offset records to get the next 20 records using the same function loop.

gameid is zero on the first call and on the second call the gameid is 21.

$result = new ArrayObject();

  
$count = 0;
foreach($response as &$game) {
    
    $game  = get_object_vars($game);
         
    if ($game['gameType'] == $gametype )
    {   
        $result->append(array($game['gameName'], $game['gameType']));
        if ($count == $gameid+19) break;
        $count ++ ;
        
    }       
    
}

Thank You

1 Answers

I think you should use the concept of page size and page index.

In you case seem like you want page size of 20. Sending second request with gameid mean you want page size 20 and page index 1 (instead of 0).

So consider code like this:

$count = 0;
$pageSize = 20; // this can be const or come as param
$pageIndex = 0; // this should be as params
foreach($response as &$game) {

    $game  = get_object_vars($game);
     
    if ($game['gameType'] == $gametype ) {
        $count++ ;
        if ($count > ($pageSize * $pageIndex))
            $result->append(array($game['gameName'], $game['gameType']));
        // if you over the request chunk break
        if ($count > ($pageSize * ($pageIndex + 1)) break; 
        
    
    }       

}
Related