[Solved] Looping through JSON decoded object

Hi all

Having a small issue trying to figure out the basics to loop through an object and display some data.

//The $ouput variable holds the JSON below
$output = json_decode($outputDetails);

JSON for viewing:

{
  "results": [
    {
      "formatted_address": "Address Name 1, United Kingdom",
      "geometry": {
        "location": {
          "lat": 00.0000000,
          "lng": -0.0000000
        },
      },
      "name": "Item Name 1",
      "types": [
        "type1",
        "type2",
        "type3"
      ],
      "user_ratings_total": 0000
    },
    {
      "formatted_address": "Address Name 2, United Kingdom",
      "geometry": {
        "location": {
          "lat": 00.0000000,
          "lng": -0.0000000
        },
      },
      "name": "Item Name 2",
      "types": [
        "type1",
        "type2",
        "type3"
      ],
      "user_ratings_total": 0000
    },
    {
      "formatted_address": "Address Name 3, United Kingdom",
      "geometry": {
        "location": {
          "lat": 00.0000000,
          "lng": -0.0000000
        },
      },
      "name": "Item Name 3",
      "types": [
        "type1",
        "type2",
        "type3"
      ],
      "user_ratings_total": 0000
    }
  ]
}

Now when I try and display and loop through this data I keep getting

Notice : Trying to get property of non-object in…

What am I doing wrong?

foreach($output as $item){
  echo $item->results->formatted_address;
  echo "<br>";
  echo $item->results->name;
}

Thanks
Barry

By default the json_decode() function will return an array, but you appear to be treating the sub-arrays as objects.

To return an object, set the second parameter in the function to true.

$output = json_decode($outputDetails, true);

https://www.php.net/manual/en/function.json-decode.php

I have tried both ways still getting the same error?

Something to do with
$item->results->formatted_address;

Do I need something like
$item->results[0]->formatted_address;

Barry

You’re right, now I read it again. :blush:

assoc
When TRUE , returned objects will be converted into associative arrays.

Try var_dump the output to see the types you are dealing with at each level.

That should be:

foreach ($output->results as $item){
  echo $item->formatted_address;
  echo "<br>";
  echo $item->name;
}

There are multiple results, and you loop over them.

The way you coded it every item in the JSON (not sure what those would be, there is only a single “results” key) has a “results” key - which is not the case.

Your code would work correctly on this JSON:

[
    {
        "results: {
            "formatted_address": "Foo",
            "name": "Blah"
        }
    },
    {
         "results": {
             "formatted_address": "Foo again",
             "name": "Dunno"
         }
    }
]
1 Like

Actually what you’ll get is NULL because the string as provided is not valid JSON.

I go back to the previous discussion that James_Hibbard and I had on the differences between a Javascript Object, and JSON.

Your dangling commas (at the end of the ‘location’ objects), and numbers with more than 1 0 in front of the decimal point, are invalid JSON. (“00” is not a valid Number. It would work as a string, though!)

Your JSON, properly formatted, is:

{
  "results": [
    {
      "formatted_address": "Address Name 1, United Kingdom",
      "geometry": {
        "location": {
          "lat": 0.0000000,
          "lng": -0.0000000
        }
      },
      "name": "Item Name 1",
      "types": [
        "type1",
        "type2",
        "type3"
      ],
      "user_ratings_total": 0
    },
    {
      "formatted_address": "Address Name 2, United Kingdom",
      "geometry": {
        "location": {
          "lat": 0.0000000,
          "lng": -0.0000000
        }
      },
      "name": "Item Name 2",
      "types": [
        "type1",
        "type2",
        "type3"
      ],
      "user_ratings_total": 0
    },
    {
      "formatted_address": "Address Name 3, United Kingdom",
      "geometry": {
        "location": {
          "lat": 0.0000000,
          "lng": -0.0000000
        }
      },
      "name": "Item Name 3",
      "types": [
        "type1",
        "type2",
        "type3"
      ],
      "user_ratings_total": 0
    }
  ]
}

The problem is, the JSON is pulled from an API query and I have no control over the formatting :thinking:

Actually a google map query if it helps
$outputDetails=file_get_contents('https://maps.googleapis.com/maps/api/place/textsearch/json?query=...');

The location was an example and most will be something like, as example:

"lat": 51.5070795,
"lng": -0.0756271

If I can’t change the formatting is there a way to fix it?
You mentioned as a string?

And what about the PHP code/format?

Plus if you can send the link to previous discussion I’ll take a look :nerd_face:

Thanks
Barry

The previous discussion was James pointing out to me that dangling commas at the end of objects is valid in Javascript objects:

<script>
let f = { "thing":"stuff",} <--valid
</script>

but it is NOT valid as a JSON string. Why? Because Javascript don’t stick to their own standards, was my conclusion. :stuck_out_tongue: (It’s got something to do with validation.)

Numbers are valid if they conform to standard number formats (floats, for example, are fine, positive or negative, but “00.0000” is not a valid number because it begins with multiple 0’s.), so i wouldnt worry about those.

I would assume google would return a valid JSON string. Check to see whether you’ve introduced these commas:

      "geometry": {
        "location": {
          "lat": 00.0000000,
          "lng": -0.0000000
        },  <-- this one, here.
      }

or if they’re in the original output.

Cool :grinning:
I’m sure I’ve come up against this issue before aswell.

While I check on a couple of things, I am using the below snippet which works ok on a single place when I echo $lat I get the value
$lat = $output->results[0]->geometry->location->lat;

It’s when I need to loop through a big dataset of multiply places I start getting the errors, I thought I was maybe just writing the PHP wrong?

Barry

Okay, if you’re able to access elements in the object, then yes, google has spat back a valid JSON, it was just the one that you posted in your original post was invalid :slight_smile:
Looping through the set as @rpkamp pointed out in Post 5 should work. If it doesnt, please post an ACTUAL example of a set that failed.

Yes I done a var_dump($output); then pasted this code into a formatter, I think this might of added the comas we see above. I didn’t realise :slightly_smiling_face:

The var_dump($output); output has no commas at all.

I’ve just tested and updated @rpkamp solution - It works! :grin:
I tried before must of changed something :upside_down_face:

Great - and cheers all!

Barry :nerd_face:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.