PHP Json解码对象存在

时间:2017-10-21 15:59:25

标签: php json foreach decode

我如何从“玩家”中获得“游戏”并且值为“730”的所有“加速器”? 它显示:
 注意未定义的属性:第31行的stdClass :: $ gameid 因为“gameid”并不存在于每个元素中

代码:

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

}   

我的json:

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

    }
}

非常感谢。最诚挚的问候。

1 个答案:

答案 0 :(得分:4)

更改

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

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

$mydata->steamid

相同

因为不是每个玩家都有gameid,所以最好还是检查一下:

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