2013-05-03 33 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