创建新表行 - PHP while 循环
我试图这样做,每当我的 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
。有人可以帮助我吗?
I am trying to do so whenever my while loop reach each 4 result (4,8,12,16 etc) it will create a new table row.
It should be like this:
[table row]
[data] [data] [data] [data]
[/table row]
[table row]
[data] [data] [data] [data]
[/table row]
and so on...
Currently I have this:
<?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; ?>
Right now, it just generates this:
[table row]
[data] [data] [data] [data] [data] [data] etc.
[/table row]
I am just not sure how to use the $i
in this example. Can someone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我能想到的两个解决方案。
检查 i 何时等于 for 然后插入该行并将 i 重置回 0。
或者,查看它是否能被 4 整除,然后插入该行。 (这可能更好,因为这样 i 将等于数据量。)
或者第二种方法:
Two solutions I can think of.
Either check when i is equal to for and then insert the row and reset i back to 0.
Or, see if it is exactly divisible by 4 and then insert the row. (Which is probably better because then i will equal the amount of data.)
Or the second method:
首先,将数据放入数组
接下来,使用 array_chunk() 将其拆分为多个嵌套数组
最后,在模板中使用2个嵌套的foreach循环来输出
而且,看在上帝的份上,学会缩进你的代码
另外,您不应该使用 mysql_num_rows() 来计算行数。
请改用
SELECT count(*)
。First, get your data into array
Next, use array_chunk() to split it into several nested arrays
Finally, in the template use 2 nested foreach loops to output
And, for God's sake, learn to indent your code
Also, you should NOT count rows by using mysql_num_rows().
Use
SELECT count(*)
instead.