我正在使用foreach循环从facebook中的图形API获取图像。
这是我的json decode的回复:
{
"data": [
{
"name": "Person 1",
"id": "12345678",
"picture": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/123456789_123456_789456.jpg"
},
{
"name": "Person 2",
"id": "12345679",
"picture": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/123456789_123456_789457.jpg"
}
],
"paging": {
"next": "https://graph.facebook.com/me/friends?access_token=.....&fields=name,id,picture&limit=5000&offset=5000&__after_id=..."
}
}
这是我的PHP:
$url = "https://graph.facebook.com/". $uid ."/friends?access_token=". $access_token ."&fields=name,id,picture";
$users = json_decode(file_get_contents($url));
echo $access_token .'<br><br>';
foreach ($users as $name => $value) {
foreach ($value as $entry) {
//Loop for profile pics
if ($entry->picture) {
echo '<a href="https://www.facebook.com/profile.php?id=' . $entry->id . '" target="_blank">' . '<img src="'. $entry->picture . '" class="profile-thumb' . $entry->name . '" id="'. $entry->id .'"></a>';
}
}
}
这很好,因为它正确地拉动了图像的路径,但它给了我这个错误:
Notice: Trying to get property of non-object in C:\inetpub\wwwroot\feref.com\facebook\test-app\friends.php on line 50
我认为这是数组中'paging'对象的结果。
如何防止此错误?也就是说,如何从循环中排除'paging'对象?
答案 0 :(得分:1)
请尝试使用if (isset($this->picture))
。这将测试图片属性是否存在。
答案 1 :(得分:1)
而不是遍历整个结果,只迭代数据数组。
声明$ users;
后添加此行$data = $users->('data');
然后做
foreach($data as $entry){
if(isset($entry->picture)){
echo ...
}
}