我有一个来自mysql的数组,现在我正在尝试使用while循环将其放入一个包含4列的表中。我的方法是,当$counter%4==0
时,我回显</tr>
,以便每4个项目排列成一行。但是我无法得到我想要的结果,所以有人能告诉我问题出在哪里或者为我提供更好的方法吗?这是我的代码:
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<?php
$query1 = "SELECT * FROM post WHERE post_status='New' AND post_type='Facilities' AND post_keywords='icon'";
$run1 = mysql_query($query1);
$counter=0;
while($row1 = mysql_fetch_array($run1)){
$post_id = $row1['post_id'];
$post_title = $row1['post_title'];
$post_date = $row1['post_date'];
$post_author = $row1['post_author'];
$post_keywords = $row1['post_keywords'];
$post_type =$row1['post_type'];
$post_content = $row1['post_content'];
$post_status =$row1['post_status'];
if($counter%4==0){
echo '<tr>';
}
?>
<td>//here is the content from the array
<div id="<?php echo $post_id?>" class="FacItem" onmousedown="function onmousedown() { fac_change('down','<?php echo $post_id?>') }" onmouseup="function onmouseup() { fac_change('up','<?php echo $post_id?>') }" onmouseover="function onmouseover() { fac_change('over','<?php echo $post_id?>') }" onmouseout="function onmouseout() { fac_change('out','<?php echo $post_id?>') }"><a href="?page_id=282"><?php echo $post_content?></a></div>
</td>
<?php
if($counter%4==0){
echo '</tr>';
}
$counter++;
}
?>
</tbody>
</table>
答案 0 :(得分:0)
您的第二次有条件检查是错误的。原因是您要在添加四个项目时输出</tr>
。目前,</tr>
正在插入第0个项目(即0,4,8等)。因此,您应该使用$counter % 4 == 3
,而是正确插入</tr>
元素:
// process to follow when the new row is being started
if ($counter % 4 == 0) {
// start `tr` element here..
echo '<tr>';
// your code ..
}
// process to follow when 4 items have been counted for
if ($counter % 4 == 3) {
// end `tr` element here..
echo '</tr>';
// your code ..
}
$counter++;
答案 1 :(得分:-1)
问题是你在循环的同一轮打开和关闭行
您需要重新安排此代码:
<?php
if($counter%4==0)
{
echo '</tr>';
}
$counter++;
到
<?php
$counter++;
if($counter%4==0)
{
echo '</tr>';
}
现在,当计数器为0时,启动一个新行,然后在关闭行之前变为1 if if语句执行...然后对于每个第4个值,计数器变为4(或4的倍数) )在关闭行之前,执行关闭行if语句。
由于下次循环执行时计数器仍然是4的倍数,因此会打开一个开口,但计数器在此之后变为1,因此不会调用关闭。
实施例
Loop # Counter at <tr> if stmt Counter at </tr> if stmt
1 0 <tr> 1
2 1 2
3 2 3
4 3 4 </tr>
5 4 <tr> 5
6 5 6
7 6 7
8 7 8 </tr>