0

I have a question about querying JSON structures that make use of nested objects. In order to explain, I will use some examples.

For Examples Sake, the variable $json is a JSON file:

movies [{"name":"good movie", "poster":"link"}]  

Normally after I've used the json_decode() function on a JSON file I can do something like

$newFiles = $json["movies"];

foreach ($newFiles as $file) {
$name = $file["name"]; }

But, lets say I have this JSON File:

movies[{"name":"good movie", "poster": {"original":"link", "smaller":"link"}}]

How would I get the value of "original", I've tried doing something like:

$newFiles = $json["movies"];

foreach ($newFiles as $file) {
$poster = $file["poster" -> "original"]; }

That, however, doesn't work. I can't find the appropriate syntax to query this. Any help appreciated, thanks in advance!

1
  • Is the answer provided is answering the question? Commented Apr 9, 2014 at 18:46

1 Answer 1

1

When you decode your json with json_decode(), set the second parameter to true, as so:

<?php
$movies = '[{"name":"good movie", "poster": {"original":"link", "smaller":"link"}}]';
$movieArray = json_decode($movies,true);

foreach($movieArray as $movie){
    print_r($movie['poster']['original']);
}
?>

This will allow you to convert returned objects into associative arrays. Therefore it is possible to do something like $movie['poster']['original'].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.