[英]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.我有一个 PHP 键/值数组,我想从那里获取一个值并将其显示在一个 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.使用 PHP foreach 索引参考,这使您能够获取键或值。
$parsed = json_decode($homepage,true);
foreach ($parsed['data'] as $key => $values){
echo $values['rating'];
}
http://www.php.net/manual/en/control-structures.foreach.php http://www.php.net/manual/en/control-structures.foreach.php
$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.注意, json_decode()默认返回 object。 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如果你不传递第二个参数,你会得到一个 object 而不是一个数组,见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.这些值是 stdClass 对象,而不是 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...注意我正在使用
->
运算符来访问 object 属性...
Rating is a subarray of array ['data'], so: Rating 是数组 ['data'] 的子数组,因此:
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'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.