简体   繁体   中英

How to Access JSON Element

I have one json i wanted to print "formatted_address" element from that json

Json

{
   "html_attributions" : [],
   "results" : [
      {
         "formatted_address" : "Narayan Peth, Pune, Maharashtra 411030, India",
         "geometry" : {
            "location" : {
               "lat" : 18.515797,
               "lng" : 73.852335
            }
         },
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
         "id" : "3a25975b3806df28aa79ac4a8d954c307be4aa57",
         "name" : "Aditya Medical",
         "place_id" : "ChIJJxwmOHDAwjsRjRDO4LnGJ-I",
         "reference" : "CmRSAAAA3E7ih55-2BZjRQcw_URQ2gwi8eWb5HU6hdfNUj_TqtDJ7TtASVMowcuWMkohNjp7F6UKuGsMuR-IlzZEt4YUJyzNxzWg-TYy6hyN8P5n2asAO6ztZeU3oHZdH7OBFFW_EhBe4cQbAU99oILcDmvv_gOhGhR7jzP0Z9-mDrncd5Gr9hOY7aOqRg",
         "types" : [ "pharmacy", "health", "store", "point_of_interest", "establishment" ]
      }
   ],
   "status" : "OK"
}

I tired to print using but unable to print it.

foreach (json_decode($address[0]->Response) as $obj){
     print_r($obj['results']['formatted_address']);
}

You need to set second param as true to get json as array. Also your formatted_address is agin inarray so need to pass index in it

foreach (json_decode($address[0]->Response, true) as $obj){
     print_r($obj['results'][0]['formatted_address']);
}

DEMO

That can be a solution :

$jsonAsArray = json_decode($yourJson, true);
$results = $array["results"][0];

var_dump($results['formatted_address']);

Good luck

Try

foreach (json_decode($address[0]->Response, true) as $obj){
     print_r($obj['results']['formatted_address']);
}

json_decode has a second parameter to determine the returned result format - object or array .

I Try like @Plamen Nikolov, but but it doesn't work. And I Try change 'True' to 1 it's work!

foreach (json_decode($address[0]->Response, 1) as $obj){
     print_r($obj['results']['formatted_address']);
}

Try

foreach (json_decode($address[0]->Response)->results as $obj){
     print_r($obj->formatted_address);
}

json_decode($address[0]->Response) will give you an object. You should not use like array. so you should use "->" instead of array form. Better you can put the result on foreach and get the data of formatted_address from that $obj

--

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