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


Parsing Json response using PHP with space in array key

我有一个邮政编码为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"
   }
 }
}

您需要将它们放在一个带单引号的大括号内:

$place_name = $response->places[0]->{'place name'};
echo $place_name;

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