为foreach提供的参数无效()
问题描述:
我完全不知道我现在做错了什么。我觉得我精神疲惫,因为我完全无能为力。以下是我正在使用的代码:为foreach提供的参数无效()
if(empty($this->updates) || !is_array($this->updates))
return null;
foreach($this->updates as $update)
这是失败的。但是,如果我在foreach之前(和之后)执行print_r($ this-> updates),那么它工作得很好。为什么当我尝试在foreach中使用它时,它假装数组不存在?
样品的print_r($这个 - >更新):
Array
(
[0] = Array
(
[id] => 1
[name] => test
)
[1] = Array
(
[id] => 2
[name] => rawr
)
)
答
既然你不知道什么是$this->updates
,我可以简单地认为它不是一个数组:你foreach
使用它之前,你可以使用is_array
测试。在这里,您有两种选择:
1-将empty()
替换为!is_array()
以检查$this->updates
是否有效。如果它是空的,也不要紧,在foreach
会干脆什么也不做......
if(!is_array($this->updates))
return null;
foreach($this->updates as $update)
或者如果foreach
是不是你做的唯一的处理:
if(empty($this->updates) || !in_array($this->updates))
return null;
foreach($this->updates as $update)
2-部队$this->updates
到是一个数组
if(empty($this->updates))
return null;
foreach((array) $this->updates as $update)
答
貌似$this->updates
不是空的,但它不是一个数组。
if(is_array($this->update)) {
foreach($this->updates as $update) {
.....
}
}
+0
$ this-updates肯定有条目,对于我正在处理的特定代码,有27个数组在更新中。我在原始问题中发布了print_r示例的结果。 – Nathan 2010-09-28 13:38:31
如果您尝试将*数组以外的任何事物*传递给'foreach',通常会发生此错误。你的'print_r'返回了什么? – 2010-09-28 13:12:59
我们可以看到'print_r'的结果吗? – fredley 2010-09-28 13:13:02
你能告诉使用var_dump($ this-> updates)的结果吗?另外,你应该添加if(!isset($ this-> updates)|| empty($ this-> updates)) – Shikiryu 2010-09-28 13:14:19