Reputation: 27058
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?
Upvotes: 2
Views: 5527
Reputation: 30012
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'];
}
http://www.php.net/manual/en/control-structures.foreach.php
Upvotes: 3
Reputation: 2133
done by dumping your example)
foreach ($parsed->data as $key => $values){
echo $values->rating;}
Upvotes: 1
Reputation: 50612
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...
Upvotes: 0
Reputation: 73031
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);
Upvotes: 1
Reputation: 9671
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.
Upvotes: 0
Reputation: 3432
The root node for "parsed" is data which is an array so you probally want..
foreach($parsed['data'] as $key => $value) {
echo $value['rating'];
}
Upvotes: -1
Reputation: 18859
Rating is a subarray of array ['data'], so:
foreach ($parsed['data'] as $key => $values){
echo $values['rating'];
}
Upvotes: -1