0

I have a json result from an URL:

{
        "result": [{
            "user.name": "Spider Man",
            "user": "a4ac7bfe6f581640a62d3c31be3ee4dc"
        }, {
            "user.name": "Bat Man",
            "user": "af406b85e4b13500b95fa1eeac1ce626"
        }, {
            "user.name": "Iron Man",
            "user": "18ed9aba4ffb07006979ab6ba110c757"
        }, {
            "user.name": "Ant Man",
            "user": "877a503a98cc4200b95f526ea1ece471"
        }, {
            "user.name": "Captain America",
            "user": "8ec0d9634f2f22004b19ca1f0310c791"
        }]
    }

How to create a foreach loop to get the following output:

Spider Man
Bat Man
Iron Man
Ant Man
Captain America

And the same for the user-values in the json.

I tried following code but I can't figure it out:

$json = file_get_contents($queryURL, false, $context) or die ("keine verbindung");
$array = json_decode($json, true);
foreach($array as $data) {
    $data->user;
}

Thanks for your help.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • When you pass true as a second parameter to `json_decode($json, true)`, this will convert it into an array, so you need to use something like `$data['elementName']` – Nigel Ren Oct 24 '18 at 19:17
  • You don't even need a loop for this, just do `echo implode('
    ', array_column($array, 'user.name'));`
    – GrumpyCrouton Oct 24 '18 at 19:21

1 Answers1

0

You decoded as an array not an object. Also, there is another level result:

foreach($array['result'] as $data) {
    echo $data['user'];
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87