Finding nested items in JSON object or associative array using PHP


I had this problem recently when I used made a call to Yahoo Finance’s Stock quotes API for my Chinese website about US Stocks.

Yahoo’s API returns the stock data in JSON form, but you can choose to handle it as a php object or associative array.

First, this post by Michael Nitschinger really helped me see my choices: Handling-JSON-like-a-boss-in-PHP.

The problem was that the information I wanted about the stock was nested deep in the JSON. So it seemed I had two choices, to treat the data like a PHP Object or Associative array.

First, you need to use PHP to decode the information correctly. If you want an object, you need to use:

$result = json_decode($string);

If you want to use it like an associative array, use:

$result = json_decode($string, true);

Then to grab nested items within the data, you have to grab it with code like below:

If the data is in object form, use:

$lastTrade = $data->query->results->quote[0]->LastTradePriceOnly;

To grab nested results like a associate array, use this style:

$lastTrade = $data["query"]["results"]["quote"][0]["LastTradePriceOnly"];

, ,

Leave a Reply

Your email address will not be published. Required fields are marked *