lol
lol

Reputation: 13

Why can't I access this json to php array?

I am trying to get stock prices from this api using curl

//Initialize cURL.
$ch = curl_init();
 
//Set the URL that you want to GET by using the CURLOPT_URL option.
curl_setopt($ch, CURLOPT_URL, 'https://cloud.iexapis.com/stable/stock/market/batch?symbols=aapl,msft&types=quote&filter=latestPrice&token=(redacted)');
 
//Set CURLOPT_RETURNTRANSFER so that the content is returned as a variable.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
//Set CURLOPT_FOLLOWLOCATION to true to follow redirects.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
 
//Execute the request.
$data = curl_exec($ch);
 
//Close the cURL handle.
curl_close($ch);
 
$stockdata = json_decode($data, true);

Right now I am getting this error: Notice: Undefined offset: 0

Here is the json I have converted into an array:

{"AAPL":{"quote":{"latestPrice":425.04}},"MSFT":{"quote":{"latestPrice":205.01}}}

Here is my code I am using to try and access the array, later I want to loop through all of the prices.

echo $stockdata[0]['quote']['latestPrice'];

Upvotes: 1

Views: 44

Answers (1)

Markus Zeller
Markus Zeller

Reputation: 9135

When you use an associated array, it is not numeric indexed anymore and you need to access its key by name which is 'AAPL'.

echo $stockdata['AAPL']['quote']['latestPrice'];

prints out

425.04


Update 1

When you do not know the first key, just get it like this

echo $stockdata[array_keys($stockdata)[0]]['quote']['latestPrice'];

Explanation
array_keys($stockdata) will give you another array with all keynames as a numeric index based array. With [0] you access the first element (0th element) which is 'AAPL' in this example.


Update 2

Based on comments for looping through, you could do it like this

foreach($stockdata as $stock => $data) {
    echo "{$stock} => {$data['quote']['latestPrice']}\n";
}

AAPL => 425.04
MSFT => 205.01

Upvotes: 2

Related Questions