【问题标题】:PHP Json decode object existPHP Json解码对象存在
【发布时间】:2018-04-02 13:40:33
【问题描述】:

如何从“gameid”存在且值为“730”的玩家那里获得所有“steamids”? 它显示:
注意 未定义的属性:第 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"
            }
        ]

    }
}

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

【问题讨论】:

  • 在 foreach 和 if($mydata->gameid 中以小写字母开头 players
  • @splash58 谢谢,但它告诉我:通知未定义的属性:第 31 行的 stdClass::$gameid 因为“gameid”并不存在于每个元素中

标签: php json foreach decode


【解决方案1】:

改变

$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

【讨论】:

  • 谢谢,但它告诉我:通知未定义属性:第 31 行的 stdClass::$gameid 因为“gameid”并不存在于每个元素中
  • 更新了答案
猜你喜欢
  • 2016-07-22
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 2023-04-09
相关资源
最近更新 更多