Alex Rivera | Logout

How to decode a JSON String with several objects in PHP?

Asked 2010-04-01T11:54:19.477
20

I know how to decode a JSON string with one object with your help from this example How to decode a JSON String

But now I would like to improve decoding JSON string with several objects and I can't understand how to do it.

Here is an example:

{ "inbox": [
  { "firstName": "Brett", "lastName":"McLaughlin" },
  { "firstName": "Jason", "lastName":"Hunter" },
  { "firstName": "Elliotte", "lastName":"Harold" }
 ],
"sent": [
  { "firstName": "Isaac", "lastName": "Asimov" },
  { "firstName": "Tad", "lastName": "Williams" },
  { "firstName": "Frank", "lastName": "Peretti" }
 ],
"draft": [
  { "firstName": "Eric", "lastName": "Clapton" },
  { "firstName": "Sergei", "lastName": "Rachmaninoff" }
 ]
}
  1. How to make just one foreach() to decode above JSON string?
  2. How to detect object's names: inbox, sent or draft on this foreach()?
Edit
Report

1 Answer

8

You can use the json_decode function to decode the JSON string :

$json = <<<JSON
{ "programmers": [
  { "firstName": "Brett", "lastName":"McLaughlin" },
  { "firstName": "Jason", "lastName":"Hunter" },
  { "firstName": "Elliotte", "lastName":"Harold" }
 ],
"authors": [
  { "firstName": "Isaac", "lastName": "Asimov" },
  { "firstName": "Tad", "lastName": "Williams" },
  { "firstName": "Frank", "lastName": "Peretti" }
 ],
"musicians": [
  { "firstName": "Eric", "lastName": "Clapton" },
  { "firstName": "Sergei", "lastName": "Rachmaninoff" }
 ]
}
JSON;

$data = json_decode($json);


Then, to see what the data looks like, you can dump it :

var_dump($data);


And you'll see you have an object containing three arrays, each one containing other sub-objects :

object(stdClass)[1]
  public 'programmers' => 
    array
      0 => 
        object(stdClass)[2]
          public 'firstName' => string 'Brett' (length=5)
          public 'lastName' => string 'McLaughlin' (length=10)
      1 => 
        object(stdClass)[3]
          public 'firstName' => string 'Jason' (length=5)
          public 'lastName' => string 'Hunter' (length=6)
      ...
  public 'authors' => 
    array
      0 => 
        object(stdClass)[5]
          public 'firstName' => string 'Isaac' (length=5)
          public 'lastName' => string 'Asimov' (length=6)
      ...

Which means you know how to access your data.


For example, to display the list of the programmers, you could use :

foreach ($data->programmers as $programmer) {
  echo $programmer->firstName . ' ' . $programmer->lastName . '<br />';
}


Which would get you the following output :

Brett McLaughlin
Jason Hunter
Elliotte Harold

                        
                        
answered 2010-04-01T12:06:39.513

Your Answer