0

I have an API which is returning some nested JSON data with multiple levels. My PHP code to loop through is below but I'm not getting any output:

    $data = json_decode($output, true);     

    foreach($data as $item){

        $title = $item->events->name->text;
        echo $title;
    }

An example of the data can be found here: https://i.sstatic.net/eAtrI.png

I am trying to print the text name of each of the events (events->name->text)

4
  • you should use foreach($data->events as $item){ Commented Jul 4, 2015 at 14:37
  • I get a syntax error: Invalid argument supplied for foreach() Commented Jul 4, 2015 at 14:39
  • That's because events is an array collection of objects, not an object. foreach($data['events'] as $item) Commented Jul 4, 2015 at 14:40
  • you need foreach($data['events'] as $item){} (because you have decoded the json into an associative array) Commented Jul 4, 2015 at 14:41

1 Answer 1

4

There is a problem in your code, when you decode the json string, you use:

$data = json_decode($output, true);     

It is converting everything to "array" (http://php.net/manual/en/function.json-decode.php), so you cannot access it like if they were objects.

You have to do:

foreach($data as $item){

    $title = $item["events"]["name"]["text"];
    echo $title;
}

Hope this helps!

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.