0

我在访问 JSON 中的元素时遇到了一些问题。这是我的代码:

$raw_json = '{
        "players": [
            {
                "steamid": "76561197960435530",
                "communityvisibilitystate": 3,
                "profilestate": 1,
                "personaname": "Robin",
                "lastlogoff": 1365134746,
                "profileurl": "http://steamcommunity.com/id/robinwalker/",
                "avatar": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4.jpg",
                "avatarmedium": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_medium.jpg",
                "avatarfull": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_full.jpg",
                "personastate": 0,
                "realname": "Robin Walker",
                "primaryclanid": "103582791429521412",
                "timecreated": 1063407589,
                "loccountrycode": "US",
                "locstatecode": "WA",
                "loccityid": 3961
            }
    }
}';
$data = json_decode($raw_json);
print $data->players{'realname'};

我的问题是 - 我怎样才能访问像 personname 或 realname 这样的数组?

4

3 回答 3

3

您使用的是花括号而不是方括号。正确的语法是

$data->players['realname']

也就是说,您在数组中有一个对象,因此通过键访问它也不起作用。你需要这样的东西

$data->players[0]

此外,您的 json 无效,因此您应该修复它。验证 json 的有用工具是http://json.parser.online.fr/

于 2013-04-11T16:14:16.167 回答
1

首先,您JSON的格式无效,并且该解码甚至无法正常工作。尝试

<?php
$raw_json = '
{
    "players": [
        {
            "steamid": "76561197960435530",
            "communityvisibilitystate": 3,
            "profilestate": 1,
            "personaname": "Robin",
            "lastlogoff": 1365134746,
            "profileurl": "http://steamcommunity.com/id/robinwalker/",
            "avatar": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4.jpg",
            "avatarmedium": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_medium.jpg",
            "avatarfull": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_full.jpg",
            "personastate": 0,
            "realname": "Robin Walker",
            "primaryclanid": "103582791429521412",
            "timecreated": 1063407589,
            "loccountrycode": "US",
            "locstatecode": "WA",
            "loccityid": 3961
        }
    ]
}
';
$data = json_decode($raw_json);
print_r( $data->players[0]); // or
echo $data->players[0]->personaname;
?>
于 2013-04-11T16:21:47.660 回答
0

尝试这个:

$data = json_decode($raw_json);
echo $data->players['realname'];

或者您可以通过以下方式查看数据格式

print_r($data);

或者

var_dump($data);
于 2013-04-11T16:17:44.820 回答