PHP: How to traverse through a JSON Object CodeUnit 06 NOV 2012

JSON has become just as big as XML in terms of being the format used to transfer data between AJAX driven web services, meaning that as a PHP developer you will no doubt be doing a lot of dealing with JSON objects.

The default way of grabbing JSON data returned by a web service is to call the built in json_decode function which generates what is known as a stdClass. These can be traversed much as you would a normal array using loops:

$jsondatastdclass = json_decode($jsoninput);

foreach ($jsondatastdclass as $object)
  foreach ($object as $property=>$value)
     echo $property." has the value ". $value;

It’s not great, but it does work. However, later version of PHP do allow you to add a second parameter when calling the json_decode function, namely a boolean which then forces the function to return a normal associative array.

In practice:

$jsondataarray = json_decode($jsoninput, true);

echo $jsondataarray['data'][0];

And now you know.

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.