[英]Getting: ' Trying to get property of non-object' when trying to access the value in an array of objects
So from a Get request I get back a response in this structure:因此,从 Get 请求中,我得到了这个结构的响应:
{
"chromeosdevices" : [
{
"somekey" : "somevalue",
"annotatedUser" : "annotatedUserValue",
"activeTimeRanges" : [
{
"date" : "dateValue",
"activeTime" : "activeTimeValue"
}
],
"somekey" : "somevalue",
},
]
}
How can I access both DateValue and ActiveTimeValue?如何同时访问 DateValue 和 ActiveTimeValue?
I have tried it with this code:我已经用这段代码试过了:
$dec = json_decode($response);
$filteredResults= array();
if (! empty($dec->chromeosdevices)) {
foreach ($dec->chromeosdevices as $chromeosdevice) {
$user['annotatedUser'] = $chromeosdevice->annotatedUser;
$user['activeTimeRanges_date'] = $chromeosdevice->activeTimeRanges->date;
$user['activeTimeRanges_activeTime'] = $chromeosdevice->activeTimeRanges -> activeTime;
$filteredResults[] = $user;
}
}
echo '<pre>';print_r($filteredResults);echo '</pre>';
However, I only get back the annotatedUser, but not the date and active time.但是,我只取回了 annotatedUser,而不是日期和活动时间。 Why is that?这是为什么?
As it is another object in an array use $chromeosdevice->activeTimeRanges[0]->date;
因为它是数组中的另一个 object,所以使用$chromeosdevice->activeTimeRanges[0]->date;
That is in an array so maybe another loop would be the safest way to deal with this那是在一个数组中,所以也许另一个循环是处理这个问题的最安全方法
$dec = json_decode($response);
$filteredResults= array();
if (! empty($dec->chromeosdevices)) {
foreach ($dec->chromeosdevices as $chromeosdevice) {
$user = []; // init and remove last loops info
$user['annotatedUser'] = $chromeosdevice->annotatedUser;
foreach ($chromeosdevice->activeTimeRanges as $tr) {
$user['activeTimeRanges_date'][] = $tr->date;
$user['activeTimeRanges_activeTime'][] = $tr->activeTime;
}
$filteredResults[] = $user;
}
}
echo '<pre>';print_r($filteredResults);echo '</pre>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.