I have a PHP key/value array and I want to grab a value from there and display it in a div.
So far I have:
$homepage = file_get_contents('http://graph.facebook.com/1389887261/reviews');
$parsed = json_decode($homepage);
I want to get the values out of the key/value pair array like this:
foreach ($parsed as $key => $values){
echo $values['rating'];
}
But this does not retrieve the value. What am I doing wrong?
Use the PHP foreach index reference, this gives you the ability to grab the key or the value.
$parsed = json_decode($homepage,true);
foreach ($parsed['data'] as $key => $values){
echo $values['rating'];
}
$rating = $parsed->data[0]->rating;
Does it work for you?
foreach ($parsed['data'] as $key => $values){
echo $values['rating'];
}
Note , json_decode() returns object by default. You need to update the following to do the above:
$parsed = json_decode($homepage, true);
done by dumping your example)
foreach ($parsed->data as $key => $values){
echo $values->rating;}
If you don't pass the second parameter, you'll get back an object instead of an array, see http://php.net/json_decode
$parsed = json_decode($homepage,true);
foreach ($parsed['data'] as $key => $values){
echo $values['rating'];
}
will do the trick for you.
The values are stdClass objects, not arrays. So, to loop:
$homepage = file_get_contents('http://graph.facebook.com/2345053339/reviews');
$parsed = json_decode($homepage);
foreach($parsed->data as $values) {
echo 'Rating:'.$values->rating;
}
Note I am using the ->
operator to access object properties...
Rating is a subarray of array ['data'], so:
foreach ($parsed['data'] as $key => $values){
echo $values['rating'];
}
The root node for "parsed" is data which is an array so you probally want..
foreach($parsed['data'] as $key => $value) {
echo $value['rating'];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.