【问题标题】:Decoding JSON using PHP使用 PHP 解码 JSON
【发布时间】:2015-12-31 18:32:23
【问题描述】:

请原谅我这个问题很简单,但我对使用 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'];

非常感谢!

【问题讨论】:

    标签: php json


    【解决方案1】:

    你应该这样做:

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

    输出:

    12 小时 27 分钟

    请注意,在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
    )
    

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

    $json = json_decode($content); // without true
    echo $json->rows[0]->elements[0]->duration->text;
    

    输出:

    12 小时 27 分钟

    【讨论】:

    • @Oren,没问题,我很乐意提供帮助。当数组中只有一项时,更容易错过它们...
    猜你喜欢
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2013-11-05
    • 2011-09-10
    相关资源
    最近更新 更多