2014-03-05 21 views
0

這裏是代碼,而該代碼產生以下輸出:screenshot of output的foreach反破 - 列出了許多在同一行

的想法是有不同的頁眉每次的牀的數量變化。

$tableTop = '<table> ... <tbody>'; 
$tableBottom = '</tbody> </table>'; 

$last_bed = null; 

foreach ($unitsForSaleData as $row) { 
    if($units_for_sale['beds'] == 0){ 
    if ($last_bed == null) { 
     echo '<h1> Studios For Sale </h1>'; 
     echo $tableTop; 
     $last_bed = $units_for_sale['beds']; 
     } 

    } else { 
     if ($units_for_sale['beds'] !== $last_bed) { 
      if ($last_bed !== null) { // End previous table 
       echo $tableBottom; 
      } 
      echo '<h1>'.$units_for_sale['beds'].' Bedroom Condos For Sale </h1>'; 
      echo $tableTop; // Start new table 
      $last_bed = $units_for_sale['beds']; 
     } 
    } 

?> 
<tr> ... </tr> 

<?php 
} // end loop 
+0

你能給我們一個你正在循環的數組的例子嗎? – Pattle

+0

你是什麼意思?我在代碼中添加了更詳細的內容。問題在於,第一個塊中的每個項目都圍繞它自己的表格。查看屏幕截圖 –

回答

0

isset而不是== null來解決它。這裏是完整的代碼,需要這樣做的其他人的完整代碼:

$tableTop = '<table> ... <tbody>'; 
$tableBottom = '</tbody> </table>'; 

$last_bed = null; 

foreach ($unitsForSaleData as $row) { 
    if($units_for_sale['beds'] == 0){ 
    if (!isset($last_bed)) { 
     echo '<h1> Studios For Sale </h1>'; 
     echo $tableTop; 
     $last_bed = $units_for_sale['beds']; 
     } 

    } else { 
     if ($units_for_sale['beds'] !== $last_bed) { 
      if ($last_bed !== null) { // End previous table 
       echo $tableBottom; 
      } 
      echo '<h1>'.$units_for_sale['beds'].' Bedroom Condos For Sale </h1>'; 
      echo $tableTop; // Start new table 
      $last_bed = $units_for_sale['beds']; 
     } 
    } 

?> 
<tr> ... </tr> 

<?php 
} // end loop 
+1

我會建議使用empty()而不是!isset(),因爲它在更大範圍的空值上返回TRUE。 –

+0

謝謝你,我現在就做這個改變 –