2010-09-28 195 views
1

我完全不知道我现在做错了什么。我觉得我精神疲惫,因为我完全无能为力。以下是我正在使用的代码:为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 
    ) 
) 
+1

如果您尝试将*数组以外的任何事物*传递给'foreach',通常会发生此错误。你的'print_r'返回了什么? – 2010-09-28 13:12:59

+0

我们可以看到'print_r'的结果吗? – fredley 2010-09-28 13:13:02

+0

你能告诉使用var_dump($ this-> updates)的结果吗?另外,你应该添加if(!isset($ this-> updates)|| empty($ this-> updates)) – Shikiryu 2010-09-28 13:14:19

回答

1

既然你不知道什么是$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) 
+0

$ this-updates已经是一个数组了,我在原始问题中发布了print_r的结果 – Nathan 2010-09-28 13:37:50

+0

@Atrox,这段代码是否执行过两次?也许第一次通过可行,但第二次通过却失败(反之亦然)?如果'$ this-> updates'总是**实际上是一个数组,那么'foreach'不会失败 – 2010-09-28 15:39:10

+0

它在一个页面上执行了大约90次,有时它可以工作,有时它不工作如果我使用print_r在foreach之前,它100%的工作时间。 – Nathan 2010-09-28 15:40:23

1

貌似$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

相关问题