PHP stdclass json解码

时间:2012-11-29 10:45:53

标签: php

我正在尝试从json_decode输出中获取一些值。我有一个在授予访问权限后连接到Tumblr API的脚本。解码object stdClass后,我已经到了这一步。我现在遇到的问题是试图只回显博客的“名称”和“追随者”数。下面的示例有两个博客而不是一个。所以博客名称在下面的例子中是“blogone”和“blogtwo”。

 {"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"}]}}}

问题是我如何回应每个博客的博客“名称”和“粉丝”数。有时候只有一个博客,有时可能会有多个博客。

谢谢。

1 个答案:

答案 0 :(得分:1)

$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;