PHP - 创建带有分隔列的动态 html 表


PHP - create dynamic html table with spacer columns

我正在尝试使用php创建一个动态网格(HTML表(。

我需要制作一个每行 5 列的表格,所有奇数列的宽度为 32%,而偶数列将为空,但宽度为 2%,用作间隔符。

我还需要它,所以如果任何行没有 3 个奇数列,即使它们是空的,它也必须生成其余的 5 列。

我已经设法做到了,所以它创建了 3% 宽度的 32% 列,并在需要时添加空 TD,我无法创建较小的 2% 列。

这将用作 HTML 电子邮件的表格网格

这是我目前的工作,但只有 3 列

<?php 
    $test = array(1,2,3,4,5);
    $count = 0;
?>
<html>
<head>
<style>
.test {border: 1px solid #ccc;}
</style>
</head>
<body>
<table cellspacing="0" cellpadding="0" border="0" width="650">
    <?php foreach($test as $t): ?>
    <?php if ($count % 3 == 0) echo "<tr>";  # new row ?>
    <td width="32%" class="test">
        <p>ddfhfdhfgh</p>
        <p>sdgdfgdgd</p>
    </td>
    <?php $count++; ?>
    <?php if ($count % 3 == 0) echo "</tr>'n";  # end row ?>
    <?php endforeach; ?>
    <?php if ($count % 3 != 0): ?>
    <?php while ($count++ % 3): ?>
    <td width="32%">&nbsp;</td>
    <?php endwhile; ?>
    </tr>
    <?php endif; ?>
</table>
</body>
</html>

我尝试添加这个,但它弄得一团糟。

<?php if ($count % 3 == 0) echo "<tr>";  # new row ?>
    <?php if ( $count & 1 ): ?>
        <td width="32%" class="test">
            <p>ddfhfdhfgh</p>
            <p>sdgdfgdgd</p>
        </td>
    <?php else: ?>
        <td width="2%">&nbsp;</td>
    <?php endif; ?>
<?php $count++; ?>

我只需要一个表格,中间有 3 个大列和 2 个间隔列

我认为这应该可以解决问题。

你让它变得比它需要的要复杂一些。

首先,您可以使用像这样foreach ($array as $index => $value)foreach语法,这样就不需要保留自己的计数器。

其次,您基本上希望每隔一列采用不同的大小,因此请使用% 2而不是% 3和简单的if then else构造。

如果你不使用 PHP 的每一行周围的 php start 和stop 标签<?php ... ?>,如果你有多个连续的 php 代码,只需使用一行在第一行上方启动解释器,在最后一行之后使用一个,它也使代码更容易阅读。否则,它往往会使试图阅读和理解代码的大脑变得紧张。

<?php 
    $test = array(1,2,3,4,5);
?>
<html>
<head>
<style>
.test {border: 1px solid #ccc;}
</style>
</head>
<body>
<table cellspacing="0" cellpadding="0" border="0" width="650">
<?php 
    echo '<tr>';
    foreach($test as $i => $t): 
        if ( $i % 2 == 0 ) :
            echo '<td width="32%" class="test">';
                echo '<p>ddfhfdhfgh</p>';
                echo '<p>sdgdfgdgd</p>';
            echo '</td>';
        else :
            echo '<td width="2%" class="test">&nbsp;</td>';
        endif;
    endforeach;
    // if array has less than the expected 5 occ add blank columns
    if ( $i < 5 ) :
        $i++;
        for ( $i ; $i < 5; $i++ ) :
            if ( $i % 2 == 0 ) :
                echo '<td width="32%" class="test">Filler</td>';
            else :
                echo '<td width="2%" class="test">&nbsp;</td>';
            endif;
        endfor;
    endif;
    echo '</tr>';
?>
</table>
</body>
</html>