PHP address array decoded from JSON

I am loading a JSON array and decode it into a PHP array

$jsonfile = file_get_contents('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=demo'); 
$jsonarray = json_decode($jsonfile); 
var_dump($jsonarray);

      

So good so far that I end up with an array that looks like this:

object(stdClass)#1 (2) { 
    ["Meta Data"]=> object(stdClass)#2 (5) { 
        ["1. Information"]=> string(49) "Daily Prices (open, high, low, close) and Volumes" 
        ["2. Symbol"]=> string(5) "AAWVX" 
        ["3. Last Refreshed"]=> string(10) "2017-06-30" 
        ["4. Output Size"]=> string(9) "Full size" 
        ["5. Time Zone"]=> string(10) "US/Eastern" 
    } 
    ["Time Series (Daily)"]=> object(stdClass)#3 (105) { 
        ["2017-06-30"]=> object(stdClass)#4 (5) { 
            ["1. open"]=> string(7) "10.5100" 
            ["2. high"]=> string(7) "10.5100" 
            ["3. low"]=> string(7) "10.5100" 
            ["4. close"]=> string(7) "10.5100" 
            ["5. volume"]=> string(1) "0" 
        } 
        ["2017-06-29"]=> object(stdClass)#5 (5) { ["1. open"]=> string(7) "10.4800" ["2. high"]=> string(7) "10.4800" ["3. low"]=> string(7) "10.4800" ["4. close"]=> string(7) "10.4800" ["5. volume"]=> string(1) "0" } 
        ["2017-06-28"]=> object(stdClass)#6 (5) { ["1. open"]=> string(7) "10.5600" ["2. high"]=> string(7) "10.5600" ["3. low"]=> string(7) "10.5600" ["4. close"]=> string(7) "10.5600" ["5. volume"]=> string(1) "0" } ...

      

But when I try to access an array like

var_dump($jsonarray['Meta Data']);

      

This does not work.

+3


source to share


1 answer


This is because it is not an array object after json_decode

no parameters, it is a stdClass object. When you decode json array, if you want array object you need to set 2nd parameter ( $assoc

boolean) to true

. Therefore, you must have

$jsonfile = file_get_contents('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=demo'); 
$jsonarray = json_decode($jsonfile,true); 
var_dump($jsonarray);

      



so that it becomes an array object. (Note the changes I made to the second line by adding true

to the function json_decode

.

More information about parameters json_decode

can be found in php.net

+9


source







All Articles