来自json的Foreach空

时间:2012-04-25 12:48:12

标签: php json foreach

我有以下网址:

https://graph.facebook.com/123456/likes?access_token=__ACCESS_TOKEN__&format=json

然后我做了:

$likesList = json_decode(file_get_contents("https://graph.facebook.com/123456/likes?access_token=$access_token&format=json"),true);

产生例如

{
"data": [

  {
     "name": "yo yo yo",
     "category": "Entertainer",
     "id": "45640987076",
     "created_time": "2012-04-18T16:14:09+0000"
  },
  {
     "name": "Tony Smith",
     "category": "Musician/band",
     "id": "456456456456",
     "created_time": "2012-02-22T06:56:18+0000"
  },
  {
     "name": "Stations",
     "category": "Company",
     "id": "567657567",
     "created_time": "2012-01-30T23:08:39+0000"
  }

]

}

然后我要列出例如所有返回的名字都是这样的:

foreach ($likesList->data as $element2){ 

    $name = $element2[name];

    echo $name; 

}

但它是空的?

2 个答案:

答案 0 :(得分:3)

请参阅数据结构的this visualization

当您收到阵列时,您需要$list["data"]而不是$list->data。另外,不要忘记引用数组键"name"

答案 1 :(得分:2)

foreach ($likesList['data'] as $element2){ 

     $name = $element2['name'];

     echo $name; 
}

在参数为true的json_decode之后,您将拥有关联数组。您可以通过字符串键访问值。就像上面的例子一样。