2012-02-26 46 views
0

有沒有人知道這個解決方案?數組中相同鍵的總和值 - Facebook Graph API

我想用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" 
    } 
} 

回答

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 
) 
+0

那做的人。謝謝! – 2012-02-26 11:21:21