How to page a foreach from a file_get_contents?

0

I am querying an API that gives me data formatted in JSON, I collect through file_get_contents and then print all values using a foreach. But there are many values, more than 5,000 items, I need to page them, I tried to limit them using an array_slice but I can not display the rest of the values when changing the number of pages.

I am using the following code to collect data:

$url            = 'URL_DA_API';
$servers_zip    = file_get_contents($url);
$servers_raw    = gzdecode($servers_zip);
$json           = json_decode($servers_raw, true);

To create the loop use the following:

foreach (array_slice($json['GET'], 0, 50) as $index=>$sv)

Finally my pagination looks like this:

function paginacao($quantreg,$numreg,$url){
        global $paginas;
        global $pg;
        $quant_pg = ceil($quantreg/$numreg);
        $quant_pg++;

        // Verifica se esta na primeira página, se nao estiver ele libera o link para anterior
        if ($pg > 0) { 
            echo '<li class="prev"><a href="'.$url.'&pg='.($pg-1).'">Anterior</a></li>';
        } 

        // Faz aparecer os numeros das página entre o ANTERIOR e PROXIMO
        for($i_pg=1;$i_pg<$quant_pg;$i_pg++) { 
                // Verifica se a página que o navegante esta e retira o link do número para identificar visualmente
                if ($pg == ($i_pg-1)) { 
                        echo '<li class="active">'.$i_pg.'</li>';
                } else {
                        $i_pg2 = $i_pg-1;
                        echo '<li><a href="'.$url.'&pg='.$i_pg2.'">'.$i_pg.'</a></li>';
                }
        }

        // Verifica se esta na ultima página, se nao estiver ele libera o link para próxima
        if (($pg+2) < $quant_pg) { 
                echo '<li class="next"><a href="'.$url.'&pg='.($pg+1).'">Próximo</a></li>';
        }
}

The first page is displaying everything perfect, number of items, number of pages, clicking on a number "page 58" it returns the url of page 58 but with the values on page 1.:

Does anyone help me?

    
asked by anonymous 03.09.2017 / 02:47

1 answer

0

You need to page the data in array_slice. Considering that the first page has index zero, it would look something like this:

foreach (array_slice($json['GET'], $pag * $reg_por_pag, $reg_por_pag) as $index=>$sv)
    
03.09.2017 / 04:40