2013-05-03 98 views
0

我從例如SDK的Facebook的這個簡單的代碼:我如何解析Facebook的PHP圖形api的JSON輸出?

if ($user) { 
try { 
$user_profile = $facebook->api('/me/friends'); 
} catch (FacebookApiException $e) { 
error_log($e); 
$user = null; 
} 
} 

如果我user_profile結果打印$的朋友在此格式列表:

[206] => Array 
      (
       [name] => name 
       [id] => 00000000 
      ) 

是否有可能訪問這些數組的字段? 比如我想只打印朋友的名字

+0

嘗試$ user_profile [206] ['friends']? – vishal 2013-05-03 10:38:41

+0

使用foreach循環。 – Rikesh 2013-05-03 10:39:27

回答

0

僅打印朋友的名字,通過主陣列/對象只是循環:

foreach($user_profile as $k => $friend) 
{ 
    echo $friend['name'].' - '.$user_profile[$key]['id'].'<br/>'; 
} 

要訪問特定的朋友:

echo $user_profile[11]['name']; 

這反映了陣列中第11個朋友的名字。將兩者結合使用函數(或方法)獲得給定好友的索引:

public function getFriendIndex($name) 
{ 
    foreach($this->user_profile as $index => $friend) 
    { 
     if ($friend['name'] === $name) 
     {//returns the index of $name's friend data 
      return $index; 
     } 
    } 
    return null;//friend doesn't exist... 
} 
+0

第一個代碼僅打印2個空行而不打印名稱。 – user840718 2013-05-03 11:02:09

+0

@ user840718:我編輯了我的答案,告訴我你現在看到了什麼(也是'var_dump($ friend)' – 2013-05-03 11:05:38

+0

謝謝,我總是看到相同的兩條空行 – user840718 2013-05-03 11:12:22