在循环中处理嵌套的json

时间:2014-05-31 14:37:05

标签: php json

json_encoded之后的json

 {
   "data":[
      {
         "name":"JIN",
         "id":"100007934492797"
      },
      {
         "name":"aris",
         "id":"100008128873664"
      },
      {
         "name":"Madm",
         "id":"34234234"
      }
   ],
   "paging":{
      "next":"https://graph.facebook.com/v1.0/1380314981/friends?limit=5000&offset=5000&__after_id=enc_AeyRMdHJrW0kW9vIZ41uFPXMPgE-VwRaHtQJz2JWyVc0hMl9eOG10C6JWjoCO8O2E4m24EPr28gIt9mxQR8oIQmN"
   }
}

我想在db中存储我的json的名称和ID。但是当我使用for循环时,偏移有问题,我怀疑它是json的最后一部分。如何删除分页部分?我试过了

foreach($friends as friend){
    echo friend[0]->name;
}

1 个答案:

答案 0 :(得分:0)

首先,您的原始代码永远不会起作用:

foreach($friends as friend){
echo friend[0]->name;
}

friend的引用应该在他们面前$制作$friend。然后,要解决更大的问题,只需使用嵌套的foreach循环:

$json = <<<EOT
{
  "data": [
        {
          "name": "JIN", 
          "id": "100007934492797"
        }, 
        {
          "name": "aris", 
          "id": "100008128873664"
        }, 
        {
          "name": "Madm", 
          "id": "34234234"
        }
      ], 
      "paging": {
        "next": "https://graph.facebook.com/v1.0/1380314981/friends?limit=5000&offset=5000&__after_id=enc_AeyRMdHJrW0kW9vIZ41uFPXMPgE-VwRaHtQJz2JWyVc0hMl9eOG10C6JWjoCO8O2E4m24EPr28gIt9mxQR8oIQmN"
      }
}
EOT;

$friends = json_decode($json);

foreach($friends as $friend_data){
  foreach($friend_data as $friend){
    echo $friend->name . '<br />';
  }
}

这个的输出是:

JIN
aris
Madm

此外,如果使用数组对您更有意义,您可以通过将第二个参数设置为json_decode来设置true以返回数组。以下是重构代码示例:

$friends = json_decode($json, true);

foreach($friends as $friend_data){
  foreach($friend_data as $friend_key => $friend_value){
    if (isset($friend_value['name'])) {
      echo $friend_value['name'] . '<br />';
    }
  }
}