我需要在文件test.json中解析一些JSON。
{
"players":
[
{ "SteamId":123, "Username":"Bob", "Kills":5, "Deaths":7, "Rank":1 },
{ "SteamId":456, "Username":"Nick", "Kills":3, "Deaths":2, "Rank":2 },
{ "SteamId":789, "Username":"Moses" "Kills":8, "Deaths":1, "Rank":3 }
]
}
如何循环并显示我的数据。到目前为止我的代码var_dump给了我一个NULL
$raw_data = file_get_contents('test.json');
$data = json_decode($raw_data, true);
var_dump($data);
答案 0 :(得分:2)
一旦你提到撒母提到的逗号,你的代码就可以了。
要循环并打印一些值,它们看起来像:
foreach($data["players"] as $player){
print "Steam ID: ".$player['SteamId'];
print "Username: ".$player['Username'];
print "Kills: ".$player['Kills'];
print "Deaths: ".$player['Deaths'];
print "Rank: ".$player['Rank'];
}
这可以改进为自动使用Key值作为输出,具有以下内容:
foreach($data["players"] as $player){
foreach($player as $key => $value){
print $key.": ".$value;
}
}
取决于您要完成的工作以及如何查看数据,但我希望您使用的是HTML模板。