【问题标题】:php table: display 3 cells in each row [duplicate]php表:每行显示3个单元格[重复]
【发布时间】:2018-07-13 00:05:44
【问题描述】:

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

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

我需要在表格中显示 PHP 数组结果。 表格每行需要有 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>";

【问题讨论】:

  • 每个&lt;td&gt;...&lt;/td&gt; 有多少数据库行?

标签: php html-table


【解决方案1】:

使用 mod 运算符 % 检查第三个元素。例如

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

【讨论】:

  • 最后,您执行$empty_cells=$i%3 之类的操作并使用while 循环绘制$empty_cells 更多的tds。您可能会发现用变量替换文字“3”是个好主意,这样代码就可以很容易地复制并粘贴到您需要每行不同数量的 col 的其他项目中。
【解决方案2】:

试试这个

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>";

【讨论】:

    【解决方案3】:

    要实现这样的目标:

    您可以通过将其包装到它自己的提供行和列的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;
    

    一些DemoSome PHP Iterator Fun

    【讨论】:

      猜你喜欢
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 2017-10-08
      • 2017-07-01
      相关资源
      最近更新 更多