php表:每行显示3个单元格

时间:2012-02-27 11:21:15

标签: php html-table

我看了看这里: Array into a table with 5 cells in each row

但我无法调整我的代码..

我需要在表格中显示PHP数组结果。 该表每行需要3个单元格。

我不知道如何每隔3行输出<tr></tr>,如果表中包含数字,我不知道如何输出最后</tr>记录不是3的倍数。

这是我的代码:

echo "<table>";


$num=mysql_numrows($result1);
$i=0;
while ($i < $num)

{


$aaa=mysql_result   ($result1,$i,"aaa");
$bbb=mysql_result   ($result1,$i,"bbb");

echo "

<td>$aaa $bbb</td> ";

$i++;

}



echo "</table>";

3 个答案:

答案 0 :(得分:4)

使用mod运算符%来检查第三个元素。 e.g。

if($i%3 == 0) {
  // this is the third element, start a new tr here
}

答案 1 :(得分:1)

实现这样的目标:

enter image description here

您可以通过将其包装到自己提供行和列的iterator中来轻松地对事物进行配置:

/**
 * function to fetch one row from database
 */
function fetch_row($resultSet = NULL) {
    static $result;
    static $i = 0;
    if ($resultSet) {
        $result = $resultSet;
        return;
    }
    return mysql_fetch_assoc($result);
}

fetch_row($result1); // initialize fetch function

$it = new FetchIterator('fetch_row');

$table = new TableIterator($it, 5);

if ($table->valid()) : ?>

<table border="1">

    <?php foreach ($table as $row => $columns) : ?>

        <tr class="<?php echo $row % 2 ? 'odd' : 'even'; ?>">

            <?php foreach ($columns as $index => $column) : ?>

            <td>
                <?php if ($column) echo $column['aaa'], ' ', $column['bbb']; ?>
            </td>

           <?php endforeach; ?>

        </tr>

    <?php endforeach; ?>

</table>

<?php endif;

一些Demo并且也可以看到Some PHP Iterator Fun

答案 2 :(得分:0)

试试这个

echo "<table><tr>";
$num=mysql_numrows($result1);
$i=0;

while ($i < $num)
{
  $aaa=mysql_result   ($result1,$i,"aaa");
  $bbb=mysql_result   ($result1,$i,"bbb");
  if($i %3 ==0)
  {
     echo"</tr><tr><td> $aaa $bbb </td>";  
  }
  else
  {
    echo"<td> $aaa $bbb </td>";  
  }
  $i++;
}
echo "</tr></table>";
相关问题