Home > front end >  How do I get a list of players with foreach from my json file?
How do I get a list of players with foreach from my json file?

Time:01-09

I want a list of every player and the time. I tried <?php foreach ($status->players as $player) { echo $player.'<br />'; } ?> But that didn't work for me. Does anybody know how I can get a list of the players and the time?

    "name":"Xanth Cluster-Genesis Pt 2 1.5xXP 4xT 3xG - (v342.2)",
    "map":"Gen2",
    "password":false,
    "maxplayers":50,
    "players":[
        {
            "name":"Cody",
            "raw":{
                "score":0,
                "time":5477.548828125
            }
        },
        {
            "name":"antoniogelardi9",
            "raw":{
                "score":0,
                "time":4328.5205078125
            }
        },
        {
            "name":"yrittz",
            "raw":{
                "score":0,
                "time":671.528564453125
            }
        }
    ],
    "bots":[
        
    ],
    "connect":"0000",
    "ping":145
}

CodePudding user response:

This way:

<?php

$inputJson = 
<<<JSON
{
    "name":"Xanth Cluster-Genesis Pt 2 1.5xXP 4xT 3xG - (v342.2)",
    "map":"Gen2",
    "password":false,
    "maxplayers":50,
    "players": [
        {
            "name":"Cody",
            "raw":{
                "score":0,
                "time":5477.548828125
            }
        },
        {
            "name":"antoniogelardi9",
            "raw":{
                "score":0,
                "time":4328.5205078125
            }
        },
        {
            "name":"yrittz",
            "raw":{
                "score":0,
                "time":671.528564453125
            }
        }
    ],
    "bots":[
        
    ],
    "connect":"0000",
    "ping":145
}
JSON;

$arr = json_decode($inputJson);

foreach ($arr->players as $player) {
    echo $player->name . ": " . $player->raw->time . "\n";   
}
  •  Tags:  
  • Related