在 HTML 表格中每 n 个单元格创建一个新行 [英] creating new row every n cells in HTML table

查看:32
本文介绍了在 HTML 表格中每 n 个单元格创建一个新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

for($i=0; $i<count($gallery);$i++)
{
    $temp = array();
    $temp = $gallery[$i];
    echo "<img src='". $temp->path . "' />";

}

现在此代码将内容打印在一行中.我想每行只打印 3 个,然后创建新行并再打印 3 个,依此类推.这怎么办?

Now this code prints the content in one row. I want to print only 3 per row and then create new row and print another 3 and so on. How can this be done?

感谢支持:)

错误

遇到 PHP 错误

严重性:注意

消息:未定义偏移量:5

Message: Undefined offset: 5

文件名:views/profile.php

Filename: views/profile.php

行号:105

遇到 PHP 错误

严重性:注意

消息:试图获取非对象的属性

Message: Trying to get property of non-object

文件名:views/profile.php

Filename: views/profile.php

行号:106

推荐答案

你可以做

$n = 3;
echo "<table><tr>";
for($i=0; $i<count($gallery);$i++){
    $temp = array();
    $temp = $gallery[$i];
    echo "<td><img src='". $temp->path . "' /></td>";
    if($i % $n ==0 && $i!=0 ){
        echo "</tr><tr>";
    }
}
echo '</tr></table>';

如果您想以正确"的方式进行操作 - 通过构建语法正确的 HTML,您需要执行以下操作:

If you want to do it the "right" way - by building the syntactically correct HTML, you need to do:

$n = 3;
echo "<table><tr>"; 
$gallery_count = count($gallery);
for($i=0; $i<$gallery_count; $i++){
    $temp = array();
    $temp = $gallery[$i];
    echo "<td><img src='". $temp->path . "' /></td>";

    if($i != 0){
        if($i % $n == 0 && $i != $gallery_count-1){
            echo "</tr><tr>";
        }
        else{
            echo ""; //if it is the last in the loop - do not echo
        }
    }
}

//example - if the last 2 `td`s are  missing:
$padding_tds  = $gallery_count % $n;
if($padding_tds != 0 ){
    $k = 0;
    while($k < $padding_tds){
       echo "<td>&nbsp;</td>";
    }
}
echo '</tr></table>';

这篇关于在 HTML 表格中每 n 个单元格创建一个新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆