Search code examples
phpjsonfeed

Loop data from query


Hello I need load data from this query from 'player_list' table but now i don't know how to.. Please help

JSON

{"status":"Online",
"hostname":"[FUNPLAY.pro] AWP Ultimate | Sniper War [RAFFLES]",
"players":"6",
"slots":"24",
"map":"awp_arcade_kp",
"memory":"1192927166",
"cpu":"13",
"players_list":[{
    "name":"",
    "score":0,
    "time":40529.5703125,
    "kills":null,
    "deaths":null,
    "ping":null
    },{
    "name":"AYAYAY",
    "score":24,
    "time":1069.7547607422,
    "kills":null,
    "deaths":null,
    "ping":null
    },{
    "name":"Fresh","score":50,"time":1069.5672607422,"kills":null,"deaths":null,"ping":null},{"name":"skitels022","score":9,"time":892.56237792969,"kills":null,"deaths":null,"ping":null},{"name":"OsPa","score":22,"time":751.53881835938,"kills":null,"deaths":null,"ping":null},{"name":"xXPalacinkaXx","score":8,"time":612.87487792969,"kills":null,"deaths":null,"ping":null}]}

PHP code

$server = Json_Decode(File_Get_Contents("http://query.fakaheda.eu/217.11.249.84:27408.feed"));
foreach($server['players_list'] as $player) { 
    echo '<span class="ipsGrid_span4">'.$player->name.'</span>'; 
    echo '<span class="ipsGrid_span4">'.$player->score.'</span>'; 
    echo '<span class="ipsGrid_span4">'.$player->time.'</span>'; 
}

It throws this error

Error: Cannot use object of type stdClass as array (0)


Solution

  • Your json_decode() has a second parameter which determine the return type. By default, it will parse the JSON string into stdObject, while you access it using indexes which is wrong

    $server = Json_Decode(File_Get_Contents("http://query.fakaheda.eu/217.11.249.84:27408.feed"));
    foreach($server->players_list as $player) { 
        echo '<span class="ipsGrid_span4">'.$player->name.'</span>'; 
        echo '<span class="ipsGrid_span4">'.$player->score.'</span>'; 
        echo '<span class="ipsGrid_span4">'.$player->time.'</span>'; 
    }
    

    To parse json string into array, use json_encode($jsonString, true)

    $server = Json_Decode(File_Get_Contents("http://query.fakaheda.eu/217.11.249.84:27408.feed"), true);
    foreach($server['players_list'] as $player) { 
        echo '<span class="ipsGrid_span4">'.$player['name'].'</span>'; 
        echo '<span class="ipsGrid_span4">'.$player['score'].'</span>'; 
        echo '<span class="ipsGrid_span4">'.$player['time'].'</span>'; 
    }