有没有人知道这方面的解决方案?
我想用PHP显示不同值的总和。类似的东西:
页面帖子:(总和)
粉丝:(总和)
用户帖子:(总和)
...
这是Facebook Graph APi的JSON形式。
{
"data": [
{
"id": "SOME_ID/insights/page_stories_by_story_type/days_28",
"name": "page_stories_by_story_type",
"period": "days_28",
"values": [
{
"value": {
"page post": 357,
"fan": 229,
"user post": 84,
"question": 72,
"mention": 4
},
"end_time": "2012-01-22T08:00:00+0000"
},
{
"value": {
"page post": 356,
"fan": 229,
"user post": 85,
"question": 73,
"mention": 4
},
"end_time": "2012-01-23T08:00:00+0000"
},
{
"value": {
"page post": 401,
"fan": 231,
"user post": 88,
"question": 73,
"mention": 4
},
"end_time": "2012-01-24T08:00:00+0000"
},
],
"title": "28 Days Page Stories by story type",
"description": "28 Days The number of stories about your Page by story type. (Total Count)"
}
],
"paging": {
"previous": "https://SOME_LINK",
"next": "https://SOME_LINK"
}
}
答案 0 :(得分:1)
我不确定原因,但您提供的json没有使用标准json_decode
进行解码,因此我必须使用http://php.net/manual/en/function.json-decode.php
上的自定义函数
这是代码:
function jsonDecode($json) {
$comment = false;
$out = '$x=';
for ($i = 0; $i < strlen($json); $i++) {
if (!$comment) {
if (($json[$i] == '{') || ($json[$i] == '['))
$out .= ' array(';
else if (($json[$i] == '}') || ($json[$i] == ']'))
$out .= ')';
else if ($json[$i] == ':')
$out .= '=>';
else
$out .= $json[$i];
}
else
$out .= $json[$i];
if ($json[$i] == '"' && $json[($i - 1)] != "\\")
$comment = !$comment;
}
eval($out . ';');
return $x;
}
// decode the JSON result
$result = jsonDecode($json);
$values = $result['data'][0]['values'];
$total_values = array();
// loop through the returned values to compute the sum for each property
foreach ($values as $item) {
foreach ($item['value'] as $key => $value) {
if (isset($total_values[$key])) {
$total_values[$key] += $value;
} else {
$total_values[$key] = $value;
}
}
}
print_r($total_values);
结果是这样的:
Array
(
[page post] => 1114
[fan] => 689
[user post] => 257
[question] => 218
[mention] => 12
)