微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将JSON值转换为PHP字符串

需要从Google Maps API获取值“距离”“文本”,并将其转换为PHP字符串.

例如,https://maps.googleapis.com/maps/api/distancematrix/json?origins=TN222AF&destinations=tn225dj&mode=bicycling&language=gb-FR&sensor=false&units=imperial给了我们:

{
   "destination_addresses" : [ "New Town, Uckfield, East Sussex TN22 5DJ, UK" ],
   "origin_addresses" : [ "Maresfield, East Sussex TN22 2AF, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "3.0 mi",
                  "value" : 4855
               },
               "duration" : {
                  "text" : "22 mins",
                  "value" : 1311
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

如何将“3.0 mi”值从此JSON提要转换为PHP变量?

非常感谢!

解决方法:

$json = <<<END_OF_JSON
{
   "destination_addresses" : [ "New Town, Uckfield, East Sussex TN22 5DJ, UK" ],
   "origin_addresses" : [ "Maresfield, East Sussex TN22 2AF, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "3.0 mi",
                  "value" : 4855
               },
               "duration" : {
                  "text" : "22 mins",
                  "value" : 1311
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}
END_OF_JSON;

$arr = (json_decode($json, true));
echo $arr["rows"][0]["elements"][0]["distance"]["text"];

--output:--
3.0 mi

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐