如何使用php从json获取元素? [英] How to get element from json with php?

查看:67
本文介绍了如何使用php从json获取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

 {
   "destination_addresses" : [ "Milano, Italia" ],
   "origin_addresses" : [ "Padova PD, Italia" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "246 km",
                  "value" : 246492
               },
               "duration" : {
                  "text" : "2 ore 36 min",
                  "value" : 9388
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

在这种情况下,我想获得246公里的距离 感谢您的回复..我不知道....

i want to get distance in this case 246km Thanks for reply.. i dont know....

从:推荐答案

您可以使用json_decode将其转换为array,如下所示:

You can convert it to an array with json_decode like this:

<?php
$json = json_decode('{
   "destination_addresses" : [ "Milano, Italia" ],
   "origin_addresses" : [ "Padova PD, Italia" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "246 km",
                  "value" : 246492
               },
               "duration" : {
                  "text" : "2 ore 36 min",
                  "value" : 9388
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}',true);

var_dump($json);
?>

结果是:

array(4) {
  ["destination_addresses"]=>
  array(1) {
    [0]=>
    string(14) "Milano, Italia"
  }
  ["origin_addresses"]=>
  array(1) {
    [0]=>
    string(17) "Padova PD, Italia"
  }
  ["rows"]=>
  array(1) {
    [0]=>
    array(1) {
      ["elements"]=>
      array(1) {
        [0]=>
        array(3) {
          ["distance"]=>
          array(2) {
            ["text"]=>
            string(6) "246 km"
            ["value"]=>
            int(246492)
          }
          ["duration"]=>
          array(2) {
            ["text"]=>
            string(12) "2 ore 36 min"
            ["value"]=>
            int(9388)
          }
          ["status"]=>
          string(2) "OK"
        }
      }
    }
  }
  ["status"]=>
  string(2) "OK"
}

为了只获取您的km,您可以在此之后执行以下操作:

In order to only get your km, you can do this afterwards:

<?php
    echo $json['rows']['0']['elements']['0']['distance']['text'];
?>

这篇关于如何使用php从json获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆