2017-02-04 35 views
1

很高興你在這裏。我需要解決方案,我在這些事情上有點新手。 現在我有頁面看起來像這樣PHP造型而

1.text 2.text 3.text 4.text 

,但我需要它是這樣

1.text 2.text 
3.text 4.text 

代碼,我

<table > 
     <?php 
     for ($x = 1; $x <= 2; $x++): ?> 
     <tr> 
     <?php while($row = $choices->fetch_assoc()): ?> 
      <td><button class="pogaAtbilzuVarianti" value="<?php echo $row['id_var']; ?>" id="atbilde_a"><?php echo $row['teksts']; ?></button></td> 
     <?php endwhile; ?> 
     </tr> 
     <?php endfor; ?> 
     </table> 
+0

檢查'$ i'平均地分成兩項。如果是,請結束行並開始新行。 – miken32

+0

你已經把你的循環裏面出來了...所以你想循環你的數據庫結果在外循環(你的WHILE循環),然後執行你的內部計數檢查,爲每2個條目生成新的行。 – TimBrownlaw

+1

謝謝你的提示和提示:) @TimBrownlaw –

回答

1

for()迴路處於這個沒用,因爲它內部的while()循環將處理查詢返回的每一行。

您應該只使用while循環,然後使用計數器來判斷是否啓動新的<tr>

<table> 
<?php 
$counter = 0; 
while ($row = $choices->fetch_assoc()) { 
    if ($counter % 2 == 0) { // Start a new row before event elements 
     echo "<tr>"; 
    } 
    ?> 
    <td><button class="pogaAtbilzuVarianti" value="<?php echo $row['id_var']; ?>" id="atbilde_a"><?php echo $row['teksts']; ?></button></td> 
    <?php 
    if ($counter % 2 == 1) { // End row after odd elements 
     echo "</tr>"; 
    } 
    $counter++; 
} 
if ($counter % 2 == 1) { // End last row if it only had 1 column 
    echo "</tr>"; 
} 
?> 
</table> 
+0

非常感謝! –

0
<table > 
    <?php while($row = $choices->fetch_assoc()): 
    if(($row['id_var'] % 2) == 1) echo '<tr>'; 
    ?> 
     <td><button class="pogaAtbilzuVarianti" value="<?php echo $row['id_var']; ?>" id="atbilde_a"><?php echo $row['teksts']; ?></button></td> 
    <?php 
    if(($row['id_var'] % 2) == 0) echo '</tr>'; 
    endwhile; ?> 
</table>