PHP JSON字符串解析

asaepe 发布于 2019-03-09 json 最后更新 2019-03-09 14:35 7 浏览

我在使用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'};
我的问题是 - 我怎样才能访问像人名或真名的数组?
已邀请:

xporro

赞同来自:

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

$data->players['realname']
也就是说,你在数组中有一个对象,所以用密钥访问它也不行。你需要这样的东西
$data->players[0]
此外,你的json无效,所以你应该修复它。验证json的有用工具是此http://json.parser.online.fr/

hquia

赞同来自:

尝试这个:

$data = json_decode($raw_json);
echo $data->players['realname'];
或者你可以看到数据格式
print_r($data);
要么
var_dump($data);

zfugit

赞同来自:

首先,您的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;
?>