使用PHP在数组键中使用空格解析Json响应

sma*_*bro 2 php arrays json object

我对邮政编码API有回应.但是,由于两个单词之间的空格,我无法弄清楚如何从'地名'中获取值.不太确定从哪里开始.

object(stdClass)#1 (4) {
 ["post code"]=>
 string(5) "42223"
 ["country"]=>
 string(13) "United States"
 ["country abbreviation"]=>
 string(2) "US"
 ["places"]=>
 array(1) {
   [0]=>
   object(stdClass)#2 (5) {
     ["place name"]=>
     string(13) "Fort Campbell"
     ["longitude"]=>
     string(8) "-87.5585"
     ["state"]=>
     string(8) "Kentucky"
     ["state abbreviation"]=>
     string(2) "KY"
     ["latitude"]=>
     string(7) "36.5995"
   }
 }
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 12

你需要将它们放在带有单引号的大括号内:

$place_name = $response->places[0]->{'place name'};
echo $place_name;
Run Code Online (Sandbox Code Playgroud)

或者正如@scragar在评论中所说的那样,如果你不通过对象来访问它们,你可以放置一个true标志json_decode($response, true),这样你就可以将它们作为关联数组来访问.