user7985499
user7985499

Reputation:

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']);
}

Upvotes: 1

Views: 100

Answers (5)

Rajarathinam
Rajarathinam

Reputation: 11

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

--

Upvotes: 0

user8442578
user8442578

Reputation:

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']);
}

Upvotes: 0

Tosx
Tosx

Reputation: 606

That can be a solution :

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

var_dump($results['formatted_address']);

Good luck

Upvotes: 2

B. Desai
B. Desai

Reputation: 16436

You need to set second param as true to get json as array. Also yourformatted_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

Upvotes: 2

Plamen Nikolov
Plamen Nikolov

Reputation: 2733

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.

Upvotes: 0

Related Questions