如何从存在“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"
}
]
}
}
改变
$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