我有以下问题: 我正在使用foreach迭代一系列有效对象。在尝试访问生成的对象或其属性时,我会收到通知,我将尝试访问非对象。
以下是代码:
$schema = json_decode($_POST['d']);
foreach ($schema->node as $node) {
var_dump($node);
if ($node->status == 1) {
$data = $node->id;
}
}
var_dump输出以下内容:
object(stdClass)#5 (6) {
["status"]=>
int(0)
["id"]=>
int(1)
["title"]=>
string(6) "Sensor"
["script"]=>
string(24) "from eZness import swag;"
["x"]=>
int(60)
["y"]=>
int(80)
}
提前致谢。
更新
$schema = json_decode($_POST['d']);
foreach ($schema->node as $node) {
var_dump($node);
echo $node->status; //Funnily this works
$status = $node->status; //while this doesn't
if ($node->status == 1) { //and this doesn't as well
$data = $node->id;
}
}
但是当删除var_dump时,即使回声也不再起作用。
更新 解决。看一下应用程序的客户端部分,在$ schema->节点数组中推送NULL值时出现问题,当然这些数组都是非对象。
答案 0 :(得分:0)
您正在尝试访问不存在的$node->data
。
答案 1 :(得分:0)
或许更多的解决方法而不是答案,但是:使用
$schema = json_decode($_POST['d'],true);
When you pass true as the second parameter, you get back an associative array instead of an object.
你应该能够通过它循环:
$schema = json_decode($_POST['d'],true); foreach ($schema['node'] as $node) { if ($node['status'] == 1) { $data = $node['id']; } }