Nick Balistreri Nick Balistreri - 8 months ago 18
PHP Question

How to parse through multiple layers of JSON

I have some JSON I need to parse in a file test.json.

{ "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 }

How can I loop through and display my data. My code so far when I var_dump gives me a NULL

$raw_data = file_get_contents('test.json');

$data = json_decode($raw_data, true);



Your code is fine once you place the comma Saty mentioned.

To loop and print some values it would look something like:

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'];

This could be improved to automatically use the Key value as output with the following:

foreach($data["players"] as $player){
    foreach($player as $key => $value){
            print $key.": ".$value;

Depends what you are trying to accomplish and how the data will be viewed, but I expect you would be using HTML template.