chillers
chillers

Reputation: 1457

PHP stdclass json decode

I'm trying to get a few values from a json_decode output. I have a script that connects to Tumblr API after granting access. I have gotten to this point after decoding the object stdClass. The problem I'm having now is trying to echo out only the "name" of the blog and "follower" count. The example below has two blogs instead of one. So the blogs name are "blogone" and "blogtwo" in the example below.

 {"meta":{"status":200,"msg":"OK"},"response":{"user":{"name":"blogone","likes":0,"following":0,"default_post_format":"html","blogs":[{"name":"blogone","url":"http:\/\/blogone.tumblr.com\/","followers":234,"primary":true,"title":"Untitled","description":"","admin":true,"updated":1354139573,"posts":0,"messages":0,"queue":0,"drafts":0,"share_likes":true,"ask":false,"tweet":"N","facebook":"N","facebook_opengraph_enabled":"N","type":"public"},{"name":"blogtwo","url":"http:\/\/blogtwo.tumblr.com\/","followers":0,"primary":false,"title":"dfgdfg","description":"","admin":true,"updated":0,"posts":0,"messages":0,"queue":0,"drafts":0,"share_likes":false,"ask":false,"tweet":"N","facebook":"N","facebook_opengraph_enabled":"N","type":"public"}]}}}

The questions is how do I echo out the blog "name" and "follower" count per each blog. Sometimes there is only one blog and sometimes there can be multiple blogs.

Thank you.

Upvotes: 1

Views: 331

Answers (1)

Sergey Eremin
Sergey Eremin

Reputation: 11080

$jsonString = '{"meta":{"status":200,"msg":"OK"},"response":{"user":{"name":"blogone","likes":0,"following":0,"default_post_format":"html","blogs":[{"name":"blogone","url":"http:\/\/blogone.tumblr.com\/","followers":234,"primary":true,"title":"Untitled","description":"","admin":true,"updated":1354139573,"posts":0,"messages":0,"queue":0,"drafts":0,"share_likes":true,"ask":false,"tweet":"N","facebook":"N","facebook_opengraph_enabled":"N","type":"public"},{"name":"blogtwo","url":"http:\/\/blogtwo.tumblr.com\/","followers":0,"primary":false,"title":"dfgdfg","description":"","admin":true,"updated":0,"posts":0,"messages":0,"queue":0,"drafts":0,"share_likes":false,"ask":false,"tweet":"N","facebook":"N","facebook_opengraph_enabled":"N","type":"public"}]}}}';
$jsonObject = json_decode($jsonString);
$result = '';
foreach ($jsonObject->response->user->blogs as $blog) {
    $result .= $blog->name . ' - ' . $blog->followers . '<br/>' . "\n";
}
echo $result;

Upvotes: 1

Related Questions