phpjsonforeachdecode

PHP Json decode object exist


how can I get all "steamids" from Players where "gameid" exists and has the value "730"? It shows:

NOTICE Undefined property: stdClass::$gameid on line number 31

because "gameid" doesn't exist in every element

Code:

$players = json_decode(file_get_contents("test.json"));
foreach($players->response->Players as $mydata)
{
if($players->gameid == "730"){
echo $mydata->steamid . "\n";
}

}   

My json:

{
    "response": {
        "players": [
            {
                "steamid": "76561198273176399",
                "loccountrycode": "US"
            },
            {
                "steamid": "76561198386141115",
                "gameid": "730",
                "loccountrycode": "DE"
            },
            {
                "steamid": "76561198019025166",
                "gameid": "730",
                "loccountrycode": "RU"
            },
            {
                "steamid": "76561198010529217",
                "loccountrycode": "DK"
            }
        ]
        
    }
}

Solution

  • Change

    $players->response->Players
    if($players->gameid == "730"){
    

    To

    $players->response->players // small letter "p"
    if($mydata->gameid == "730"){
    

    It's the same as $mydata->steamid

    Since not every player has a gameid it's better to check on that aswell:

    if( isset($mydata->gameid) && $mydata->gameid === '730' ) // or check on empty if the "gameid" can be set but also can be empty