2016-09-21 51 views
1

因此,使用Latte引擎我似乎無法遍歷我的表中的每個數據行。我只能得到第一個,我已經沒有想法了!PHP - foreach沒有循環遍歷整個表

$query = $this->db->query("SELECT id,title FROM table"); 

    $array = array(); 
    while($fetch = $query->fetch_assoc()) { 
     $array = $fetch; 
    } 

    $Template["listing"] = $array; 

模板:

{foreach $listing as $item} 
    {$item["title"]}} 
{/foreach} 

回答

3

Simpliest解決方案(如果你不需要在其他地方$array變量):

$query = $this->db->query("SELECT id,title FROM table"); 

while($fetch = $query->fetch_assoc()) { 
    $Template["listing"][] = $fetch; 
} 
+0

謝謝!有趣的解決方案:)像魅力一樣工作。只要有可能,將標記爲正確。 –

3

相反的$array = $fetch,運行$array[] = $fetch,以增加更多的項目。

你正在做的是覆蓋每個循環中的數組。

+0

感謝您的輸入,但我已經嘗試過,並且對我無效。 –

+0

它爲什麼不起作用?當你這樣做時你會得到相同的結果嗎? – Phiter

+1

這比接受的答案要好,因爲它實際上解釋了OP做錯了什麼。 – Andy

0
$query = $this->db->query("SELECT id,title FROM table"); 

$array = array(); 
while($fetch = $query->fetch_assoc()) { 
    $array[] = $fetch; 
} 

$Template["listing"] = $array; 
+0

儘管此代碼可能會回答問題,但提供有關爲何和/或代碼如何回答此問題的其他上下文可提高其長期價值。不鼓勵使用僅有代碼的答案。 – Ajean

0
$query = $this->db->query("SELECT id,title FROM table"); 

$array = array(); 
while($fetch = $query->fetch_assoc()) { 
    $array[] = $fetch; 
} 
$Template = $array;