如何访问JSON元素

时间:2017-09-07 09:13:42

标签: php json

我有一个json我想从那个json

打印“formatted_address”元素

的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"
}

我累了打印但无法打印。

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

5 个答案:

答案 0 :(得分:2)

您需要将第二个参数设置为true才能将json设置为数组。你的formatted_address也是agin inarray,所以需要传递索引

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

DEMO

答案 1 :(得分:2)

这可以是一个解决方案:

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

var_dump($results['formatted_address']);
祝你好运

答案 2 :(得分:0)

尝试

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

json_decode有第二个参数来确定返回的结果格式 - objectarray

答案 3 :(得分:0)

我试着像@Plamen Nikolov,但是它没有用。我尝试改变' True'为了它的工作!

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

答案 4 :(得分:0)

尝试

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

json_decode($ address [0] - > Response)会给你一个对象。你不应该使用like数组。所以你应该使用“ - >”而不是数组形式。最好你可以将结果放在foreach上并从$ obj

获取formatted_address的数据

-