簡體   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