2

Using this below as an example of a JSON response I would get from an API using PHP

[
   {
    "profile_background_tile": true,
    "listed_count": 82,
    "status":  {
      "created_at": "Fri Apr 20 20:06:12 +0000 2012",
      "place": null,
    },
    "default_profile": false,
    "created_at": "Tue Oct 25 00:03:17 +0000 2011"
  }
]

I would use something like this...

$obj = json_decode($json);

foreach($obj as $index => $user) {
    echo $user->profile_background_tile;
    echo $user->listed_count;
    echo $user->status;    
    echo $user->default_profile;
    echo $user->created_at;
}

Now where I need some help is in the JSON response under status there is created_at and place

I do not know how to access those items?

2 Answers 2

1

You use the exact same logic, but a level deeper:

echo $user->status->created_at;
echo $user->status->place;

Here is why that works: your decoded JSON is array of objects. Each object has properties like profile_background_tile. They also have a status property, which happens to be another object, with properties created_at and place. And you access object properties with $obj->prop syntax.

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

3 Comments

That is what I had thought and I thought I had tried that with no success, I will try again
Ahh it does work, I had tried it in a smaller demo before and it wasn't working but trying it in my main class now works, thanks!
@CodeDevelopr Don't worry, you don't have to delete the comment. I updated my answer with an explanation, I hope it helps.
1

Error

Your JSON is not valid ...

Look at

"status":  {
  "created_at": "Fri Apr 20 20:06:12 0000 2012",
  "place": null,
},

there is , after "place": null which should not be there

Try

$json = '[{"profile_background_tile": "true",
    "listed_count": 82,
    "status":  {
      "created_at": "Fri Apr 20 20:06:12 0000 2012",
      "place": null
    },
    "default_profile": false,
    "created_at": "Tue Oct 25 00:03:17 +0000 2011"
  }]';

echo "<pre>";
$obj = json_decode ( $json );
foreach ( $obj as $index => $user ) {
    echo $user->status->created_at , PHP_EOL;
    echo $user->status->place , PHP_EOL;

}

Output

 Fri Apr 20 20:06:12 0000 2012

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.