2010-09-28 252 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