Patrioticcow
Patrioticcow

Reputation: 27058

PHP, get values from an array?

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

Answers (8)

Niklas
Niklas

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

Dmitri Gudkov
Dmitri Gudkov

Reputation: 2133

done by dumping your example)

foreach ($parsed->data as $key => $values){
echo $values->rating;}

Upvotes: 1

Chris Baker
Chris Baker

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

Jason McCreary
Jason McCreary

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

konsolenfreddy
konsolenfreddy

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

Stephen
Stephen

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

Berry Langerak
Berry Langerak

Reputation: 18859

Rating is a subarray of array ['data'], so:

foreach ($parsed['data'] as $key => $values){
    echo $values['rating'];
}

Upvotes: -1

Tadeck
Tadeck

Reputation: 137430

$rating = $parsed->data[0]->rating;

Does it work for you?

Upvotes: 2

Related Questions