每当我的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
。有人能帮助我吗?
答案 0 :(得分:0)
首先,将您的数据放入数组
接下来,使用array_chunk()将其拆分为多个嵌套数组
最后,在模板中使用2个嵌套的foreach循环来输出
而且,为了上帝的缘故,学习缩进你的代码
此外,您不应使用mysql_num_rows()计算行数。
请改用SELECT count(*)
。
答案 1 :(得分:0)
我能想到的两种解决方案。 检查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; ?>