【问题标题】:decode json into php variables [duplicate]将json解码为php变量[重复]
【发布时间】:2017-05-06 15:31:11
【问题描述】:

我正在尝试将 JSON 结果的内容转换为 php 变量。我使用的代码是:

$request = json_decode(file_get_contents("https://api.sunrise-sunset.org/json?lat=51.507351&lng=-0.127758&date=today"), true); 

JSON 调用的输出如下所示:

array(2) { 
     ["results"]=> array(10) { 
         ["sunrise"]=> string(10) "4:21:35 AM" 
         ["sunset"]=> string(10) "7:32:34 PM" 
         ["solar_noon"]=> string(11) "11:57:04 AM" 
         ["day_length"]=> string(8) "15:10:59"
         ["civil_twilight_begin"]=> string(10) "3:42:08 AM"
         ["civil_twilight_end"]=> string(10) "8:12:01 PM"
         ["nautical_twilight_begin"]=> string(10) "2:49:55 AM" 
         ["nautical_twilight_end"]=> string(10) "9:04:14 PM" 
         ["astronomical_twilight_begin"]=> string(10) "1:41:12 AM" 
         ["astronomical_twilight_end"]=> string(11) "10:12:57 PM" 
      } 
      ["status"]=> string(2) "OK" 
} 

如何将“日出”时间和“日落”时间放入 php 变量 $SunRiseTime 和 $SunSetTime;

非常感谢您抽出宝贵时间。

【问题讨论】:

标签: php arrays json


【解决方案1】:

简单直接。

<?php
ini_set('display_errors', 1);

$json = file_get_contents("https://api.sunrise-sunset.org/json?lat=51.507351&lng=-0.127758&date=today"); 
$array=json_decode($json,true);

echo $SunRiseTime=$array["results"]["sunrise"];
echo $SunSetTime=$array["results"]["sunset"];

输出: 4:21:35 AM 7:32:34 PM

【讨论】:

  • 完美,这正是我所需要的。非常感谢所有回复。
  • @DCJones 欢迎... :)
  • 我会尽快系统允许,谢谢。
【解决方案2】:
$SunRiseTime = $request['results']['sunrise'];
$SunSetTime  = $request['results']['sunset'];

【讨论】:

    【解决方案3】:

    使用 $$ 在 php dynamic 中定义一个变量。如果你想静态定义一个变量,直接给它赋值。

    动态的,

    $name = 'SunRise';
    $$name = $array["results"]["sunrise"];
    

    静态名称,

    $SunRise = $array["results"]["sunrise"];
    

    【讨论】:

    • 为什么不直接使用$SunRise
    • 因为这可能是动态的。如果这是静态的,你是对的。
    • 似乎是静态的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多