dongmu3457 2018-03-21 08:08 采纳率: 0%
浏览 69
已采纳

解析JSON PHP中的子文档数组

I got the following JSON string in PHP:

{  
   "status":"200",
   "message":"Saved picklist found",
   "data":{  
      "_id":{  
         "$oid":"5aab871dbcdcab3ab0005cd3"
      },
      "username":"admin",
      "list_count":"3",
      "list":[  
         {  
            "id":"1",
            "data":"AUTOGENERATED1",
            "x":"33",
            "y":"33"
         },
         {  
            "id":"2",
            "data":"AUTOGENERATED2",
            "x":"22",
            "y":"22"
         },
         {  
            "id":"3",
            "data":"AUTO",
            "x":"33",
            "y":"33"
         }
      ]
   }
}

that I decode to an array using the following:

json_decode($response, true);

I would like to loop through the array and extract for example username and list_count. I tried the following code for that:

foreach ($response['data'] as $resp) {
     echo $resp['list_count'];
}

which does not work. Any suggestions on how to extract username and list_count?

I would also like to loop through the list array and get the values for each object within that array, any suggestions on how that can be done?

  • 写回答

3条回答 默认 最新

  • dousou2911 2018-03-21 08:19
    关注

    You can use this code.

    $dd = json_decode($json,true);
    echo $dd["data"]["username"]."<br/>"; //get value of username
    
    //Loop through list to get all values
    foreach($dd["data"]["list"] as $key=>$value){
    echo $value['id']."<br/>";
    echo $value['data']."<br/>";
    echo $value['x']."<br/>";
    echo $value['y']."<br/>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助