2012-03-06 134 views
1

我有一個類系統和一個函數,它從數據庫結果做foreach。變量是在foreach中分配的,但在foreach外部是空的。PHP變量空外部Foreach?

// Top of file 
private $movieList = array(); 

if ($query->num_rows() > 0) { 
      foreach ($query->result() as $row) { 
       // add each to the array 
       $this->movieList[] = array('nid' => $row->nid, 'title' => $row->title, 'movie_pos_id' => $row->movie_pos_id); 
       print_r($this->movieList); // variable full of stuff 
      } 
      // No results found 
      return false; 
     } 

print_r($this->movieList); // variable empty 

任何想法爲什麼?

+2

你可以發佈整個代碼;我的打賭是你在循環實際運行之前打印它 – scibuff 2012-03-06 16:25:32

+0

這不是'$ query-> num_rows()> 0'。 – hakre 2012-03-06 16:25:53

回答

2

在我看來像你的行if語句永遠不會執行,因爲你總是返回假如果你有結果。檢查你的括號。您可能的意思是:

if ($query->num_rows() > 0) { 
    foreach ($query->result() as $row) { 
     // add each to the array 
     $this->movieList[] = 
      array('nid' => $row->nid, 'title' => $row->title, 
       'movie_pos_id' => $row->movie_pos_id); 
     print_r($this->movieList); // variable full of stuff 
    } 
} 
else { 
    // No results found 
    return false; 
} 

print_r($this->movieList); 
+1

大聲笑我不敢相信......大聲笑謝謝,我需要在晚上停止編碼。 – Steven 2012-03-06 16:35:15

1

您的大括號不匹配。試試這個

// Top of file 
private $movieList = array(); 

if ($query->num_rows() > 0) { 
      foreach ($query->result() as $row) { 
       // add each to the array 
       $this->movieList[] = array('nid' => $row->nid, 'title' => $row->title, 'movie_pos_id' => $row->movie_pos_id); 
       print_r($this->movieList); // variable full of stuff 
      } 
}else{ 
      // No results found 
      return false; 
} 


print_r($this->movieList); // variable empty