简体   繁体   中英

Getting nested array data from JSON

I am currently trying to retrieve some info from some json code in PHP. I have some of it achieved but I am trying to get a players name from a nested array and I am having a bit of trouble. This is the json info:

Sorry I had to post on pastebin as JSON wouldnt embed in the code box. ht tps://pastebin.com/6RZAgKFa

I have pulled in the info like so:

$json_string2 = 'URL TO JSON DATA';
$jsondata2 = file_get_contents($json_string2);
$serverinfo2 = json_decode($jsondata2,true);

And I can view it by printing it.

Now I am trying to loop through it all to just retrieve names, I am trying the following:

foreach($serverinfo2 as $playerinfo) {
                    foreach($playerinfo as $playerstuff) {
                        echo $playerstuff;
                    }
                }

But that returns the full array. I then add [name] to the end of echo $playerstuff and it returns a number 1 and a D. Not even relevant, and $playerstuff->name also doesn't work. Can anyone help me at all. Thanks :)

You can try this to achieve data from nested data from json :

<?php
$res = '[{"endpoint":"127.0.0.1","id":"2","identifiers":["STEAMID HERE","LICENSE HERE"],"name":"Deadpool","ping":"85"},{"endpoint":"127.0.0.1","id":"1","identifiers":["STEAMID HERE","LICENSE HERE"],"name":"Logan","ping":"73"}]';
$result = json_decode($res,true);
// echo '<pre>'; //print_r($result);
foreach ($result as $key => $value) {
    // print_r($value);
    echo $endpoint = 'endpoint : ' .$value['endpoint'];echo "<br/>";
    echo $name = 'name :' .$value['name'];echo "<br/>";
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM