解析JSON PHP中的子文档数组

时间:2018-03-21 08:08:48

标签: php arrays json

我在PHP中获得了以下JSON字符串:

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

我使用以下代码解码为数组:

json_decode($response, true);

我想遍历数组并提取例如username和list_count。我尝试了以下代码:

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

哪个不起作用。关于如何提取用户名和list_count的任何建议?

我还想遍历list数组并获取该数组中每个对象的值,以及有关如何完成的任何建议?

3 个答案:

答案 0 :(得分:0)

请添加以下代码,以便从JSON获取用户名和listcount。

$arr       = json_decode($response,true);
$userName  = $arr['data']['username'];
$listCount = $arr['data']['list_count'];

答案 1 :(得分:0)

您可以使用此代码。

$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 :(得分:0)

$values    = json_decode($response,true);
$username  = $arr['data']['username'];
$listCount = $arr['data']['list_count'];
if ($listCount > 0) {
    foreach ($values['data']['list'] as $list) {
        //Here you are looping inside lists and have the following
        // $list['id']
        // $list['data']
        // $list['x']
        // $list['y']
    }
}