我有一个使用mysql 填充的表
<?php $sql = mysqli_query($con, "SELECT * FROM itemList"); ?>
<table>
<?php while($row=mysqli_fetch_assoc($sql)){ ?>
<tr>
<td>
<?php echo $row['item'] . ": <input type='"checkbox'" name='"cart[]'"
value='"" . $row['item'] . "'">";?>
</td>
<td>
<?php echo $row['item'] . ": <input type='"checkbox'" name='"cart[]'"
value='"" . $row['item'] . "'">";?>
</td>
</tr>
<?php
} ?>
</table>
当前,此代码将相同的数据循环到表中的两列中。我该如何将数据循环到备用列中?
例如:
<table>
<tr>
<td>
item1
</td>
<td>
item2
</td>
</tr>
<tr>
<td>
item3
</td>
<td>
item4
</td>
</tr>
</table>
我会使用索引计数器和模运算符来检查该计数器是偶数还是不偶数。类似于:
$i = 1;
while (bla) {
$i++;
if ($i % 2 == 0) {
// even number, col 1
} else {
// uneven number, col 2
}
}
尝试这个
<?php $sql = mysqli_query($con, "SELECT * FROM itemList"); ?>
<table>
<tr>
<?php $i=1; while($row=mysqli_fetch_assoc($sql)){ ?>
<td>
<?php echo $row['item'] . ": <input type='"checkbox'" name='"cart[]'"
value='"" . $row['item'] . "'">";?>
</td>
<?php if($i%2 == 0){ echo "</tr><tr>"; } ?>
<?php $i++;
} ?>
</tr>
</table>
其他方式根据@OlivierH
对我的上述anwser 的评论
<?php
$rows = array(); while($row=mysqli_fetch_assoc($sql)){
$rows[] = $row;
}
?>
<table>
<?php $totalrows = count($rows);
if($totalrows){ ?>
<tr>
<?php $i=1; foreach($totalrows as $r){ ?>
<td>
<?php echo $r['item'] . ": <input type='"checkbox'" name='"cart[]'"
value='"" . $r['item'] . "'">";?>
</td>
<?php if($i%2 == 0 && $totalrows != $i){ echo "</tr><tr>"; } ?>
<?php $i++; } ?>
</tr>
<?php } ?>
</table>
您可以使用计数并对其进行播放:
- 对于第一项,显示
<tr>
和您的数据 - 对于第二项,显示您的数据和
</tr>
- 对于第三项,显示
<tr>
和您的数据
您可以使用%
(模运算符)。它返回除法的剩余部分。
示例:
echo 0%2; //0
echo 1%2; //1
echo 2%2; //0
echo 3%2; //1
echo 4%2; //0
...
你也可以只玩一个变量,你设置为0,1,0。。。或者。这是代码:
$sql = mysqli_query($con, "SELECT * FROM itemList");
$i = 0;
echo "<table>";
while($row=mysqli_fetch_assoc($sql)){
//create new line if this item is the first of the row (i == 0)
if($i == 0){
echo "<tr>";
}
echo "<td>" . $row['item'] . ": <input type='"checkbox'" name='"cart[]'" value='"" . $row['item'] . "'"></td>";
//if the item is the second of the row, close the tr and set i to 0
if($i == 1){
echo "</tr>";
$i = 0;
}
//else, increment i
else{
$i++;
}
}
echo "</table>";