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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题