【问题标题】:Parse Results of Google Elevation Using PHP使用 PHP 解析 Google Elevation 的结果
【发布时间】:2011-12-16 21:05:11
【问题描述】:

我是 JSON 和解析新手。从 Google Elevation API 请求海拔时,我得到以下结果。

{
  "status": "OK",
  "results": [ {
    "location": {
      "lat": 39.7391536,
      "lng": -104.9847034
    },
    "elevation": 1608.8402100
  } ]
}

解析时,不知道如何使用 json_decode 结果有效引用高程。我的删节代码如下:

$json_string = file_get_contents($url);
$parsed_json = json_decode($json_string);
$geoElevation = $parsed_json->{'elevation'};

谁能告诉我为什么我不能使用上述方法访问“海拔”值?

【问题讨论】:

    标签: php json parsing google-maps-api-3 elevation


    【解决方案1】:

    试试这个:

    $json_string = file_get_contents($url);
    $parsed_json = json_decode($json_string);
    
    echo $parsed_json->results[0]->elevation;
    

    或者如果你更喜欢使用数组:

    $json_string = file_get_contents($url);
    $parsed_json = json_decode($json_string, TRUE);
    
    echo $parsed_json['results'][0]['elevation'];
    

    第二个参数:

    当 TRUE 时,返回的对象将被转换为关联数组。 来自json_encode 手册

    【讨论】:

      【解决方案2】:

      您应该使用print_r($parsed_json) 来更好地可视化您的数据结构:

      $parsed_json
      (
          [status] => OK
          [results] => Array
              (
                  [0] => Array
                      (
                          [location] => Array
                              (
                                  [lat] => 39.739153600000001631542545510456
                                  [lng] => -104.98470340000000078362063504755
                              )    
                          [elevation] => 1608.8402100000000700674718245864
                      )
              )
      )
      

      这是一个数组,您可以使用json_decode($json_string, TRUE); 获得。这样更容易遍历条目。

      在你的情况下你想要:

       print $parsed_json["results"][0]["elevation"];
      

      通常你会想要foreach 超过数字级别。但是,如果您只期望一个结果,那么[0] 非常适合使用。

      【讨论】:

      • 感谢您的回复。所以我不正确地引用它。我必须将其解析为 Array 而不是我使用的其他方法?
      • 不,您不必这样做。但这通常会使事情变得更容易。 -- 参见 BOZs answer 了解相应的语法。结构保持不变。
      猜你喜欢
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2015-06-10
      • 2011-10-11
      • 2011-12-06
      相关资源
      最近更新 更多