【问题标题】:Parsing Json response using PHP with space in array key使用 PHP 解析 Json 响应,数组键中有空格
【发布时间】:2014-09-23 15:52:45
【问题描述】:

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

【问题讨论】:

  • 您是否考虑过使用$array_output = json_decode($str_api_response, TRUE); 将其作为数组获取,然后您可以引用您的列访问权限:echo $array_output['places'][0]['place name'];

标签: php arrays json object


【解决方案1】:

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

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

或者正如@scragar 在 cmets 中所说,如果您不方便通过对象访问它们,您可以在 json_decode($response, true) 上放置一个 true 标志,以便您可以将它们作为关联数组进行访问。

【讨论】:

  • 谢谢!如此简单,但我无法弄清楚。工作得很好!当它允许我时,我会将其标记为正确答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-29
  • 2021-08-15
  • 1970-01-01
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多