decode json into php variables [duplicate]

2020-01-20 03:41发布

问题:

I am trying to get the contents of a JSON result into php variables. The code I am using is:

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

The output of the JSON call looks like this:

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" 
} 

How can I get the "sunrise" time and the "sunset" times into php variables $SunRiseTime and $SunSetTime;

Many thanks in advance for your time.

回答1:

Simple and straight.

<?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"];

Output: 4:21:35 AM 7:32:34 PM



回答2:

$SunRiseTime = $request['results']['sunrise'];
$SunSetTime  = $request['results']['sunset'];


回答3:

use $$ to define a variable in php dynamic. If your want to static define a variable, directly assign the value to it.

dynamic,

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

static name,

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