簡體   English   中英

在循環中處理嵌套的json

[英]handling nested json in looping

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"
   }
}

我想將json的名稱和ID存儲在db中。 但是,當我使用for循環時,偏移量存在問題,我懷疑這是json的最后一部分。 如何刪除分頁部分? 我試過了

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

首先,您的原始代碼將永遠無法使用:

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

此外,如果使用數組對您更有意義,則可以始終通過將第二個參數設置為true來設置json_decode以返回數組。 這里以重構代碼為例:

$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