Search code examples
phpforeachtwitch

Possible to overide a foreach variable parameter within itself?


I have made a small script which uses the Twitch API. The API only allows a maximum of 100 results per query. I would like to have this query carry on until there are no more results.

My theory behind this, is to run a foreach or while loop and increment the offset by 1 each time.

My problem however, is that I cannot change the foreach parameters within itself. Is there anyway of executing this efficiently without causing an infinite loop?

Here is my current code:

 <?php
        $newcurrentFollower = 0;
        $offset=0;
        $i = 100;
        $json = json_decode(file_get_contents("https://api.twitch.tv/kraken/channels/greatbritishbg/follows?limit=25&offset=".$offset));
        foreach ($json->follows as $follow)
            {
                    echo $follow->user->name . ' (' . $newcurrentFollower . ')' . "<br>";
                    $newcurrentFollower++;
                    $offset++;
                    $json = json_decode(file_get_contents("https://api.twitch.tv/kraken/channels/greatbritishbg/follows?limit=25&offset=".$offset));
            }
    ?>

Using a While loop:

while($i < $total)
    {
        $json = json_decode(file_get_contents("https://api.twitch.tv/kraken/channels/greatbritishbg/follows?limit=25&offset=".$offset));
            echo $json->follows->user->name . ' (' . $newcurrentFollower . ')' . "<br>";
            $newcurrentFollower++;
            $offset++;
            $i++;
    }

Ends up echoing this (No names are successfully being grabbed): enter image description here

Here is the API part for $json->follows:

https://github.com/justintv/Twitch-API/blob/master/v2_resources/channels.md#get-channelschannelfollows


Solution

  • You can use this:

    $offset = 0;
    $count = 1;
    
    do {
        $response = json_decode(file_get_contents(
            'https://api.twitch.tv/kraken/channels/greatbritishbg/follows?limit=100&offset='  . $offset
        )); 
    
        foreach($response->follows as $follow) {
            echo $follow->user->name . ' (' . ($count++) . ')' . "</br>";
        }   
    
        $offset+=25;
    
    } while (!empty($response->follows));