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

New answer

Re your revised question: foreach actually works with properties as well as with many-valued items (arrays), details here. So for instance, with the JSON string in your question:

$data = json_decode($json);
foreach ($data as $name => $value) {
    // This will loop three times:
    //     $name = inbox
    //     $name = sent
    //     $name = draft
    // ...with $value as the value of that property
}

Within your main loop over the properties, you can use an inner loop to go over the array entries each property points to. So for instance, if you know that each of the top-level properties has an array value, and that each array entry has a “firstName” property, this code:

$data = json_decode($json);
foreach ($data as $name => $value) {
    echo $name . ':'
    foreach ($value as $entry) {
        echo '  ' . $entry->firstName;
    }
}

…will show:

inbox:
  Brett
  Jason
  Elliotte
sent:
  Issac
  Tad
  Frank
draft:
  Eric
  Sergei

Old answer(s)

Begin edit
Re your comment:

Now I would like to know how to decode JSON string with several objects!

The example you posted does have several objects, they’re just all contained within one wrapper object. This is a requirement of JSON; you cannot (for example) do this:

{"name": "I'm the first object"},
{"name": "I'm the second object"}

That JSON is not valid. There has to be a single top-level object. It might just contain an array:

{"objects": [
    {"name": "I'm the first object"},
    {"name": "I'm the second object"}
]}

…or of course you can give the individual objects names:

{
    "obj0": {"name": "I'm the first object"},
    "obj1": {"name": "I'm the second object"}
}

End edit

Your example is one object containing three properties, the value of each of which is an array of objects. In fact, it’s not much different from the example in the question you linked (which also has an object with properties that have array values).

So:

$data = json_decode($json);
foreach ($data->programmers as $programmer) {
    // ...use $programmer for something...
}
foreach ($data->authors as $author) {
    // ...use $author for something...
}
foreach ($data->musicians as $musician) {
    // ...use $musician for something...
}

Leave a Comment