PHP Json 解码对象存在

问题描述 投票:0回答:1

如何从存在“gameid”且值为“730”的玩家那里获取所有“steamid”? 它显示:

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

因为“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"
            }
        ]
        
    }
}
php json foreach decode
1个回答
5
投票

改变

$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
© www.soinside.com 2019 - 2024. All rights reserved.