Wondering why my PHP code will not display all "Value" of "Values" in the JSON data:
想知道为什么我的PHP代码不会在JSON数据中显示“值”的所有“值”:
$user = json_decode(file_get_contents($analytics));
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
}
foreach($user->data->values as $values)
{
echo $values->value . "\n";
}
The first foreach works fine, but the second throws an error.
第一个foreach工作正常,但第二个抛出错误。
{
"data": [
{
"id": "MY_ID/insights/page_views_login_unique/day",
"name": "page_views_login_unique",
"period": "day",
"values": [
{
"value": 1,
"end_time": "2012-05-01T07:00:00+0000"
},
{
"value": 6,
"end_time": "2012-05-02T07:00:00+0000"
},
{
"value": 5,
"end_time": "2012-05-03T07:00:00+0000"
}, ...
3 个解决方案
#1
38
You maybe wanted to do the following:
您可能想要执行以下操作:
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
#2
6
You need to tell it which index in data
to use, or double loop through all.
您需要告诉它要使用哪个数据索引,或者双循环遍历所有索引。
E.g., to get the values in the 4th index in the outside array.:
例如,获取外部数组中第4个索引中的值:
foreach($user->data[3]->values as $values)
{
echo $values->value . "\n";
}
To go through all:
通过所有:
foreach($user->data as $mydata)
{
foreach($mydata->values as $values) {
echo $values->value . "\n";
}
}
#3
4
$user->data
is an array of objects. Each element in the array has a name
and value
property (as well as others).
$ user-> data是一个对象数组。数组中的每个元素都有name和value属性(以及其他元素)。
Try putting the 2nd foreach
inside the 1st.
尝试将第二个foreach放在第一个。
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
#1
38
You maybe wanted to do the following:
您可能想要执行以下操作:
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
#2
6
You need to tell it which index in data
to use, or double loop through all.
您需要告诉它要使用哪个数据索引,或者双循环遍历所有索引。
E.g., to get the values in the 4th index in the outside array.:
例如,获取外部数组中第4个索引中的值:
foreach($user->data[3]->values as $values)
{
echo $values->value . "\n";
}
To go through all:
通过所有:
foreach($user->data as $mydata)
{
foreach($mydata->values as $values) {
echo $values->value . "\n";
}
}
#3
4
$user->data
is an array of objects. Each element in the array has a name
and value
property (as well as others).
$ user-> data是一个对象数组。数组中的每个元素都有name和value属性(以及其他元素)。
Try putting the 2nd foreach
inside the 1st.
尝试将第二个foreach放在第一个。
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}