santa santa - 6 months ago 48
PHP Question

Getting data from Yelp API

I'm starting to look into Yelp API. When I send a search request I get a data returned in an array $response. So If I output it like this

echo '<pre>';
print_r($response);
echo '</pre>';


I see results in the following format

stdClass Object
(
[message] => stdClass Object
(
[text] => OK
[code] => 0
[version] => 1.1.1
)

[businesses] => Array
(
[0] => stdClass Object
(
[rating_img_url] => http://s3-media2.ak.yelpcdn.com/assets/2/www/img/99493c12711e/ico/stars/v1/stars_4_half.png
[country_code] => US
...
)
)
)


So, let's say I want to get the country code, shouldn't I be able to get it with something like?

echo $response['businesses'][0]->country_code;


I'm not getting any results. What am I missing?

Answer
echo $response->businesses[0]->country_code;

businesses is a property, not an array element.

Everything below stdClass Object are properties.

Everything below => Array are Array Elements.

Let me guess, $response = json_decode(...); ?

You can tell this function to return associative arrays instead of objects by putting up the second parameter true:

$response = json_decode(..., true);

Then the values would be in:

echo $response['businesses'][0]['country_code'];