解码json响应以获取json参数值

时间:2014-03-31 20:36:11

标签: php json

这是我的json回复:

stdClass Object ( [is_claimed] => [rating] => 4 [mobile_url] => http://m.yelp.com/biz/the-waterboy-sacramento [rating_img_url] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/c2f3dd9799a5/ico/stars/v1/stars_4.png [review_count] => 455 [name] => The Waterboy [snippet_image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [rating_img_url_small] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/f62a5be2f902/ico/stars/v1/stars_small_4.png [url] => http://www.yelp.com/biz/the-waterboy-sacramento [menu_date_updated] => 1387494198 [reviews] => Array ( [0] => stdClass Object ( [rating] => 5 [excerpt] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [time_created] => 1395158338 [rating_image_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png [rating_image_small_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png [user] => stdClass Object ( [image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [id] => H0qUqWctz5Ms6qdeaIvjFw [name] => Lori T. ) [rating_image_large_url] => http://s3-media3.ak.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png [id] => bZznirkpADmW3Qcpc5u_VA ) ) [phone] => 9164989891 [snippet_text] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [image_url] => http://s3-media1.ak.yelpcdn.com/bphoto/9e5sodvvP3p6_53wOqVTcg/ms.jpg [categories] => Array ( [0] => Array ( [0] => French [1] => french ) [1] => Array ( [0] => Italian [1] => italian ) ) [display_phone] => +1-916-498-9891 [rating_img_url_large] => http://s3-media2.ak.yelpcdn.com/assets/2/www/img/ccf2b76faa2c/ico/stars/v1/stars_large_4.png [menu_provider] => single_platform [id] => the-waterboy-sacramento [is_closed] => [location] => stdClass Object ( [city] => Sacramento [display_address] => Array ( [0] => 2000 Capitol Ave [1] => Midtown [2] => Sacramento, CA 95811 ) [neighborhoods] => Array ( [0] => Midtown ) [postal_code] => 95811 [country_code] => US [address] => Array ( [0] => 2000 Capitol Ave ) [state_code] => CA ) )

我使用的是:

$response = json_decode($data);
print_r($response);
echo $response["rating"]; //Why this does not give json response value?

1 个答案:

答案 0 :(得分:2)

true传递给json_decode的第二个参数以返回一个数组(这就是您尝试访问它的方式):

$response = json_decode($data, true); // associative array returned
print_r($response);
echo $response["rating"]; // 4

<强> Manual

否则,访问rating作为您拥有的对象的属性:

$response = json_decode($data);
echo $response->rating; // 4