PHP: loop for certain chunks of a total and then rest

I'm not sure if I did this right:

I have a total number of items, say 624. I would like to make a loop that sends 7 requests, the first 6 over 100 items each, the last over the remaining 24.

So I did some math to find out how many loops I have to go through.

    // this is the total number of items
    $total = $result['total_items'];
    // if we split the total into such chunks
    $chunksize = 50;
    // we will get a rest of so many items
    $rest = $total % $chunksize;
    // so including the query for the rest, we will have to repeat the query so many times
    $queries_no = (($total-$rest)/$chunksize)+1;

The above feels kinda clumsy. Is that the right way?

PS: After that, I can repeat the query the necessary times.

    // prep loop
    $i = 0;
    $requested = 0;
    $subscribers = [];

    while ($i <= $queries_no){
        // last item
        if($i == $queries_no){
            $chunksize = $rest;
        }
        $result = $this->monkeyApp->get('lists/'.$list_id.'/members?offset='.$requested.'&count='.$chunksize);
        $subscribers = array_merge($subscribers,$result['members']);
        $requested = $requested + $chunksize;
        $i++;
    }

1 answer

  • answered 2018-11-07 23:11 user1597430

    $subscribers = [];
    
    for ($count = $chunksize, $offset = 0; $offset < $total; $offset += $chunksize)
    {
        if ($offset + $chunksize > $total)
        {
            $count = $total % $chunksize;
        }
    
        $result = $this->monkeyApp->get("lists/$list_id/members?offset=$offset&count=$count");
    
        $subscribers = array_merge($subscribers, $result['members']);
    }