使用PHP解码JSON

时间:2015-12-31 18:32:23

标签: php json

请原谅我这个问题的简单性,但我是使用API​​和JSON的新手。但我有一个JSON文件,我想打印出"文本"值"持续时间"。我怎么能这样做?

{
   "destination_addresses" : [ "San Francisco, CA, USA" ],
   "origin_addresses" : [ "Seattle, WA, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "808 mi",
                  "value" : 1299998
               },
               "duration" : {
                  "text" : "12 hours 27 mins",
                  "value" : 44846
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

我正在尝试使用:

$url = 'https://maps.googleapis.com/maps/......'
$content = file_get_contents($url);
$json = json_decode($content, true);

echo $json['rows']['elements']['duration']['text'];

非常感谢!

1 个答案:

答案 0 :(得分:1)

你应该这样做:

print(pd.read_csv('data.csv', lineterminator='\n'))

  country  metric  2011  2012
0     USA   GDP\r     7     4
1     USA  Pop.\r     2     3
2      GB   GDP\r     8     7

输出:

  

12小时27分钟

请注意,在echo $json['rows'][0]['elements'][0]['duration']['text']; 中,您标记了新数组json,因此您忘记使用[

<小时/> 这是结构(来自[SOME_NUMBER]):

print_r($json);

您也可以将其用作对象。它会是这样的:

Array
(
    [destination_addresses] => Array
        (
            [0] => San Francisco, CA, USA
        )

    [origin_addresses] => Array
        (
            [0] => Seattle, WA, USA
        )

    [rows] => Array
        (
            [0] => Array
                (
                    [elements] => Array
                        (
                            [0] => Array
                                (
                                    [distance] => Array
                                        (
                                            [text] => 808 mi
                                            [value] => 1299998
                                        )

                                    [duration] => Array
                                        (
                                            [text] => 12 hours 27 mins
                                            [value] => 44846
                                        )

                                    [status] => OK
                                )

                        )

                )

        )

    [status] => OK
)

输出:

  

12小时27分钟