繁体   English   中英

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这样的foreach语法foreach ($array as $index => $value)因此您不需要保留自己的计数器。

其次,您基本上希望其他所有列都采用不同的大小,因此请使用% 2而不是% 3并使用一个if then else构造的简单构造。

如果您在PHP的每一行中不使用php开始和停止标记<?php ... ?> ,它也使代码更易于阅读,如果您有多于一行的连续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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM