[英]Creating new table row - PHP while loop
我试图这样做,只要我的while循环达到每个4个结果(4、8、12、16等),它将创建一个新的表行。
应该是这样的:
[table row]
[data] [data] [data] [data]
[/table row]
[table row]
[data] [data] [data] [data]
[/table row]
等等...
目前我有这个:
<?php
$cat=mysql_query("SELECT * FROM kb_categories");
$i = 0;
while($catData=mysql_fetch_assoc($cat)):
$i ++;
//Select the numbers of articles inside each category.
$number=mysql_num_rows(mysql_query("SELECT * FROM kb_articles WHERE cat_id='".$catData['id']."'"));
?>
<td><img src="/themes/dream/images/icons/folder.gif"><span><?php echo $catData['name']; ?></span> (<?php echo $number; ?>)</td>
<?php endwhile; ?>
现在,它只是生成以下内容:
[table row]
[data] [data] [data] [data] [data] [data] etc.
[/table row]
我只是不确定在此示例中如何使用$i
。 有人能帮我吗?
首先,将数据放入数组
接下来,使用array_chunk()将其拆分为多个嵌套数组
最后,在模板中使用2个嵌套的foreach循环进行输出
而且,为了上帝的缘故,学会缩进代码
另外,您不应该使用mysql_num_rows()对行进行计数。
请改用SELECT count(*)
。
我可以想到两种解决方案。 检查i何时等于for,然后插入行并将i重置为0。或者,查看它是否可以被4整除,然后插入行。 (这可能会更好,因为那样的话我将等于数据量。)
<?php
$cat=mysql_query("SELECT * FROM kb_categories");
$i = 0;
while($catData=mysql_fetch_assoc($cat)) :
$i ++;
//Select the numbers of articles inside each category.
$number=mysql_num_rows(mysql_query("SELECT * FROM kb_articles WHERE cat_id='".$catData['id']."'"));
if($i==3) {
// Insert row here, probably something like this:
echo "</tr><tr>";
$i = 0;
}
?>
<td><img src="/themes/dream/images/icons/folder.gif"><span><?php echo $catData['name']; ?></span> (<?php echo $number; ?>)</td>
<?php endwhile; ?>
或第二种方法:
<?php
$cat=mysql_query("SELECT * FROM kb_categories");
$i = 0;
while($catData=mysql_fetch_assoc($cat)) :
$i ++;
//Select the numbers of articles inside each category.
$number=mysql_num_rows(mysql_query("SELECT * FROM kb_articles WHERE cat_id='".$catData['id']."'"));
if( (($i+1) % 4) == 0) {
// Insert row here, probably something like this:
echo "</tr><tr>";
}
?>
<td><img src="/themes/dream/images/icons/folder.gif"><span><?php echo $catData['name']; ?></span> (<?php echo $number; ?>)</td>
<?php endwhile; ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.