Getting only 4 items out of 1059 instead of all

1

I was able to solve my problem of picking up the date. Currently my problem is to get all users for some reason my JSon is only giving 4 items of 1059 and I want to get all of them.

<?php 
function buscaUser($user)
{
$opts = [
        'http' => [
                'method' => 'GET',
                'header' => [
                        'User-Agent: PHP'
                ]
        ]
];
$user=  $_GET['username'];
$context = stream_context_create($opts);
$content = file_get_contents('https://api.github.com/search/users?q='.$user, false, $context); 
$json = json_decode($content,true);
$jsoncount = count($json);
echo $jsoncount."<br>";
for ($numItem = 0 ; $numItem <= $jsoncount; $numItem++){

echo "<img class='img-thumbnail' width='100px' height='100px' src=".$json['items'][$numItem]['avatar_url']."><br>";
echo $json['items'][$numItem]['login']."<br>";
echo "<a href=".$json['items'][$numItem]['html_url'].">Repositorio</a><br>";
}
}
?>
    
asked by anonymous 18.10.2016 / 16:18

2 answers

3

items is array of arrays , you must specify the index, I made some minor changes to your code, see:

function buscaUser($user) {
    $opts = [ 'http' => [
              'method' => 'GET',
              'header' => [ 'User-Agent: PHP' ]
            ]];

    $context = stream_context_create($opts);
    $content = file_get_contents("https://api.github.com/search/users?q=$user", false, $context); 

    $json = json_decode($content, true);

    if ($json['total_count'] > 0) { // Se há dados
        foreach ($json['items']['0'] as $item) {
            echo $item . "<br>";
        }

        // Para acessar um item especifico
        echo $json['items']['0']['login'] . "<br>";
        echo $json['items']['0']['url'] . "<br>";
    }
}

$user = isset($_GET['username']) ? $_GET['username'] : 'NaixSpirit';
buscaUser($user);

To walk through items , you can do this:

// ...
$json = json_decode($content, true);
$json_count = count($json['items']);

if ($json_count > 0) {
    for ($indice = 0; $indice < $json_count; $indice++) {
        $login = $json['items'][$indice]['login'];
        $url =   $json['items'][$indice]['url'];

        echo "$login, $url <br>";
    }
}
    
18.10.2016 / 16:44
1

Instead of iterating the integer array (json), specify which key you want ( items ).

The code below iterates the keys total_count , incomplete_results that have scalar values (simple) so a warning is generated because the key login does not exist, the following is items as $json['items']['items'] or $json['items']['items']['login'] does not exist that generates more warnings.

To solve this, just specify the 'start point' of the array.

Switch:

foreach ($json as $json) {
   echo $json['items']['login'];
}

By:

foreach ($json['items'][0] as $item) {
    echo $item .'<br>';
}
    
18.10.2016 / 16:27