Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>New answer</h2> <p>Re your revised question: <code>foreach</code> actually works with properties as well as with many-valued items (arrays), <a href="http://php.net/manual/en/sdo.sample.getset.php" rel="noreferrer">details here</a>. So for instance, with the JSON string in your question:</p> <pre><code>$data = json_decode($json); foreach ($data as $name =&gt; $value) { // This will loop three times: // $name = inbox // $name = sent // $name = draft // ...with $value as the value of that property } </code></pre> <p>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 <em>know</em> that each of the top-level properties has an array value, and that each array entry has a "firstName" property, this code:</p> <pre><code>$data = json_decode($json); foreach ($data as $name =&gt; $value) { echo $name . ':' foreach ($value as $entry) { echo ' ' . $entry-&gt;firstName; } } </code></pre> <p>...will show:</p> <pre>inbox: Brett Jason Elliotte sent: Issac Tad Frank draft: Eric Sergei</pre> <h2>Old answer(s)</h2> <p><strong>Begin edit</strong> Re your comment:</p> <blockquote> <p>Now I would like to know how to decode JSON string with several objects!</p> </blockquote> <p>The example you posted <em>does</em> have several objects, they're just all contained within one wrapper object. This is a requirement of <a href="http://json.org" rel="noreferrer">JSON</a>; you cannot (for example) do this:</p> <pre><code>{"name": "I'm the first object"}, {"name": "I'm the second object"} </code></pre> <p>That JSON is not valid. There <em>has</em> to be a single top-level object. It might just contain an array:</p> <pre><code>{"objects": [ {"name": "I'm the first object"}, {"name": "I'm the second object"} ]} </code></pre> <p>...or of course you can give the individual objects names:</p> <pre><code>{ "obj0": {"name": "I'm the first object"}, "obj1": {"name": "I'm the second object"} } </code></pre> <p><strong>End edit</strong></p> <p>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).</p> <p>So:</p> <pre><code>$data = json_decode($json); foreach ($data-&gt;programmers as $programmer) { // ...use $programmer for something... } foreach ($data-&gt;authors as $author) { // ...use $author for something... } foreach ($data-&gt;musicians as $musician) { // ...use $musician for something... } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload