简体   繁体   English

在循环中处理嵌套的json

[英]handling nested json in looping

json after json_encoded 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"
   }
}

I want to store the name and ID of my json in db. 我想将json的名称和ID存储在db中。 But when I use for loop there's a problem with the offset, I suspect it's the last part of the json. 但是,当我使用for循环时,偏移量存在问题,我怀疑这是json的最后一部分。 How to remove the paging part? 如何删除分页部分? I tried 我试过了

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

First, your original code would never work: 首先,您的原始代码将永远无法使用:

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

Those references to friend should have $ in front of them making them $friend . 那些对friend引用应该在$前面使它们成为$friend Then to solve your larger issue, just use a nested foreach loop: 然后,要解决更大的问题,只需使用嵌套的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 />';
  }
}

And the output of this would be: 这样的输出将是:

JIN
aris
Madm

Additionally, if working with arrays makes more sense for you, you can always set json_decode to return an array by setting the second parameter to true . 此外,如果使用数组对您更有意义,则可以始终通过将第二个参数设置为true来设置json_decode以返回数组。 Here is refactored code as an example: 这里以重构代码为例:

$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 />';
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM