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...
}
Answer from T.J. Crowder on Stack Overflow
🌐
JSON Formatter
jsonformatter.org › json-parser
JSON Parser Online to parse JSON
This JSON decode online helps to decode unreadable JSON.
🌐
Json Parser Online
json.parser.online.fr
Json Parser Online
Analyze your JSON string as you type with an online Javascript parser, featuring tree view and syntax highlighting. Processing is done locally: no data send to server.
🌐
Nextjson
nextjson.com
Nested JSON Parser and Viewer Online - NextJSON
Easy-to-use Nested JSON decoder and multiple level JSON parser. Free online JSON formatter, viewer, and parser. escape, beautify, and format JSON files.
🌐
PHP
php.net › manual › en › function.json-decode.php
PHP: json_decode - Manual
Returns the value encoded in json as an appropriate PHP type. Unquoted values true, false and null are returned as true, false and null respectively. null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting ...
Top answer
1 of 2
30

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...
}
2 of 2
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
🌐
JWT
jwt.io › introduction
JSON Web Tokens - jwt.io
Decode, verify, and generate JSON Web Tokens, which are an open, industry standard RFC 7519 method for representing claims securely between two parties.
Find elsewhere
🌐
JSONLint
jsonlint.com
JSONLint - The JSON Validator
JSONLint is a validator and reformatter for JSON, a lightweight data-interchange format.
🌐
W3Schools
w3schools.com › php › func_json_decode.asp
PHP json_decode() Function
The json_decode() function is used to decode or convert a JSON object to a PHP object.
🌐
JSON Editor Online
jsoneditoronline.org
JSON Editor Online: edit JSON, format JSON, query JSON
JSON Editor Online is the original and most copied JSON Editor on the web. Use it to view, edit, format, repair, compare, query, transform, validate, and share your JSON data.
🌐
GitHub
github.com › nlohmann › json
GitHub - nlohmann/json: JSON for Modern C++ · GitHub
Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports BSON (Binary JSON), CBOR (Concise Binary Object Representation), MessagePack, UBJSON (Universal Binary JSON Specification) and BJData (Binary JData) to efficiently encode JSON values to byte vectors and to decode such vectors.
Starred by 49.1K users
Forked by 7.3K users
Languages   C++ 96.9% | CMake 2.0% | Python 0.6% | Makefile 0.3% | Starlark 0.1% | Jinja 0.1%
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.web.helpers.json.decode
Json.Decode Method (System.Web.Helpers) | Microsoft Learn
Converts data in JavaScript Object Notation (JSON) format into a data object of a specified type. public static dynamic Decode(string value, Type targetType);
🌐
Readthedocs
nbodykit.readthedocs.io › en › latest › _modules › json › decoder.html
json.decoder
[docs] def raw_decode(self, s, idx=0): """Decode a JSON document from ``s`` (a ``str`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous ...
🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
3 weeks ago - JSONDecodeError will be raised if the given JSON document is not valid. ... Decode a JSON document from s (a str beginning with a JSON document) and return a 2-tuple of the Python representation and the index in s where the document ended.
🌐
OnlinePHP
onlinephp.io › json-decode
json_decode - Online Tool
Execute and test json_decode with this online tool
🌐
Pluxbox
developers.pluxbox.com › json-decode
JSON Decode
May 27, 2024 - JSON Decode · JSON Encode · URL Decode · URL Encode · And · Or · Color · Flip · Upload File(s) Base64 Encode · Base64 Decode · Workdata · Collections and Relations · Integrations · Playground · Workdata Guide · Workflows · Workflows Guide · Monitoring ·
🌐
ConvertCSV
convertcsv.com › json-to-csv.htm
JSON To CSV Converter
You can also force double quotes around each field value or it will be determined for you. The output CSV header row is optional. See also CSV to JSON and CSV to GeoJSON Plus Convert JSON to XML, XML to JSON, JSON Lint, JSON Formatter and Analyze JSON Paths at ConvertJSON.com