我想在我的网站上显示一篇文章列表,其中包含文章下方的authour,日期和评论字段,以便用户在打开文章之前可以查看文章的评论数量。
来自facebook和im的使用图形api,每篇文章返回以下JSON代码,如何从中获取评论总数?感谢
我已经尝试过json_decode但是数组得到的数字都是零。
{
"http://www.withinzambia.com/technology-and-it/your-modem-isnt-that-fast.html": {
"comments": {
"data": [
{
"id": "10151004341202332_23086817",
"from": {
"name": "Cindi Mutale",
"id": "1045450015732187"
},
"message": "Glad someone finally pointed this out.",
"can_remove": false,
"created_time": "2012-07-02T19:46:58+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "10151002332_23094740",
"from": {
"name": "Chanda Mike",
"id": "1000034452054679"
},
"message": "my modem is 7mbps, so that's not 7MB per second?",
"can_remove": false,
"created_time": "2012-07-03T13:51:24+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "10151004341202332_23094782",
"from": {
"name": "Precious Chulu",
"id": "100242343243281187"
},
"message": "The max for the modem in the picture is 7mbps, which is actually about 900kb when you divide by 8, so you will never download at more than 1mb per second with these modems even when MTN or Airtel upgrades the network.",
"can_remove": false,
"created_time": "2012-07-03T13:57:56+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"next": "https://graph.facebook.com/10151004341202332/comments?value=1&redirect=1&limit=25&offset=25&__after_id=10151004341202332_23094782"
}
}
}
}
答案 0 :(得分:1)
<?php
...
$count = 0;
$array = json_decode($input, true);
foreach($array AS $website) {
$count += count($website['comments']['data']);
}
...
?>
$ count就是答案。
答案 1 :(得分:0)
$jsonArr = ' ..your JSON array.. ';
$decodedArr = json_decode($jsonArr);
$num_comments = count($decodedArr->{'http://www.withinzambia.com/technology-and-it/your-modem-isnt-that-fast.html'}->comments->data);
echo $num_comments;
测试并运作。 请注意,如果您将JSON加载到字符串中,就像我在这里所做的那样,需要对单引号进行转义。