简体   繁体   中英

Parse array of subdocuments in 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?

Please add below code in order to get the username and listcount from the JSON.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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