2016-06-23 15 views
1

我是PHP和Facebook PHP SDK的新手,我期待從'likes''summary'獲得Facebook頁面發佈的'like_count' 。我當前的代碼包含以下內容:從頁面發佈'total_count'發佈贊「總結」 - Facebook PHP SDK(已關閉)

$response = $fb->get('/me/posts?fields=admin_creator,likes.limit(0).summary(true)&limit=30'); 
$getLikeCount = $response->getGraphEdge()->asArray(); 
foreach($getLikeCount as $likekey){ 
    if(isset($likekey['likes'])){ 
     var_export($likekey['likes']); 
     foreach ($likekey['likes'] as $likekey){ 
      //echo $likekey['total_count'] . '<br>'; 
     } 
    } 
} 

var_export($likekey['likes']);出口空白陣列而var_export($likekey['summary']);返回null。然而,在圖形API瀏覽器,它返回如下:

{ 
     "admin_creator": { 
     "name": "NAME", 
     "id": "ID" 
     }, 
     "id": "ID", 
     "likes": { 
     "data": [ 
     ], 
     "summary": { 
      "total_count": 1022, 
      "can_like": true, 
      "has_liked": false 
     } 
     } 
    }, 

我如何可以訪問'total_count'字段,因爲通過我的'likes'和方法訪問它「summary'不起作用。

編輯:使用getGraphEdge()->asArray();將無法​​正常工作,因爲它不會返回摘要數組。我不知何故必須從getDecodedBody();或其他方法獲得值。如果我使用$getLikeCount = $response->getDecodedBody();,使用此代碼:

foreach($getLikeCount as $key){ 
    if(isset($key['admin_creator'])){ 
     echo $key['admin_creator']['name']; 
    } 
} 

它不返回任何內容。我使用'admin_creator'作爲示例,因爲它的工作原理是$getLikeCount = $response->getGraphEdge()->asArray();並且在我當前的方法中不起作用,但是我不能使用此方法,因爲我試圖從的'summary'中獲取'total_count'字段,並且'summary'未顯示在數組使用getGraphEdge()方法時只顯示使用getDecodedBody();時。我想知道是否有辦法從getDecodedBody()獲取值,或者有從summary獲得total_count字段的解決方法。

答案: 答案可以在下面找到。

回答

2

我發現周圍的工作。

解決方法需要找到帖子ID,然後再做另一個請求以僅獲取該帖子的喜歡字段。

$response = $fb->get('/me/posts?fields=admin_creator,likes.limit(0).summary(true)&limit=30'); 
$getPostID = $response->getGraphEdge()->asArray(); 
foreach($getPostID as $IDKey){ 
    if(isset($IDKey['id'])){ 
     $currentPostID = $IDKey['id']; 
     $likesResponse = $fb->get('/'.$currentPostID.'/likes?limit=0&summary=true'); 
     echo $currentPostID . '<br>'; //optional 
     $getLikeCount = $likesResponse->getGraphEdge(); 
     $currentLikeCount = $getLikeCount->getTotalCount(); 
     echo $currentLikeCount . '<br>'; 
    } 
} 
0

嘗試

$getLikeCount['likes']['summary']['total_count'] 
+0

我編輯了一下這個問題。問題似乎是'getGraphEdge() - > asArray();'不會返回'summary'數組。 – Jack

5

您可以在不進行更多API調用的情況下找到該數據。 摘要數據隱藏在該字段的元數據中。評論和反應是一樣的。

$response = $fb->get('/me/posts?fields=id,likes.limit(0).summary(true)'); 
foreach ($reponse->getGraphEdge() as $graphNode) { 
    // Some fields can have metadata 
    $likesData = $graphNode->getField('likes')->getMetaData(); 
    echo 'The total of likes for the post ID "' . $graphNode->getField('id') . '" is: '. $likesData['summary']['total_count']; 
}