【问题标题】:How can I add a new row in a table every 10 columns automatically?如何自动每 10 列在表中添加一个新行?
【发布时间】:2013-06-26 17:16:03
【问题描述】:

我有 2 个查询从数据库中提取 2 个不同的数据集 第一个包含表的标题,所以如果总结果为 10,那么我们有 10 个表的标题。

第二个将有记录,每个记录的每一列都有一个值。所以如果我有 5 条记录,这意味着第二个数据集中有 5 x 10(总标题)= 50 条记录。

我想在表格中显示的那 50 条记录。

我的方法是一次显示一条记录,但在每 10 条记录关闭后为下一行打开一条新记录。

我不确定这是否是解决这个问题的最佳方法,但我愿意接受更好的想法。

假设我的方法是一个好方法,如何在每 10 条记录后在表中创建一个新行。

我曾尝试通过在 PHP 中使用 Mod 操作来完成此操作,但这对我不起作用。

这是我当前显示数据的代码,但它没有在正确的时间/地点添加。

我的问题是如何添加修复此代码以正确显示结果?

    //count of headers  
    $total_th = count($headers);

    //generate the headers
    $report_rows = '<thead><tr><th>Company Code</th>';
    foreach($headers AS $head){
        $report_rows .= '<th>'.$head['title'].'</th>';
    }   
    $report_rows .= '</tr></thead>';


    //count of the the actual results
    $total_results = count($results);

    //create the table body
    $report_rows .= '<tbody>';

    //loop all of the records
    for($i=0; $i< $total_results; ++$i){
    $row = $results[$i];

    //start new row "Add this only once per row
        if($i == 0 ||  $i % $total_th == 0){
        $report_rows .= '<tr>';
        $report_rows .= '<td>'.$row['company_code'].'</td>';
        }

    //display all answers
    $report_rows .= '<td>'.$row['answer'].'</td>';

    //close row if the $total_th is reached 
        if( $i % $total_th == 0){
        $report_rows .= '</tr>';
        }

    }
    //close tbody and table
    $report_rows .= '</tbody>';

echo '<table class="common2">';
echo $report_rows;
echo '</table>';

【问题讨论】:

  • 循环进展如何?
  • 真的很简单,来这里之前请证明你已经做了一些尝试。
  • @Barmar 我只是尝试更新我的问题
  • 请不要转发同样的问题:stackoverflow.com/questions/17355623/…
  • @andrewsi ....你链接到这个问题

标签: php modulo


【解决方案1】:

您可以使用modulus operation

$i = 1;
foreach($records as $record){
echo $record;
if ($i % 10 == 0)
   echo '<hr />';
$i++;
}

【讨论】:

  • 由于某种原因它现在对我有用。请查看我的帖子,因为我已对其进行了修改。
猜你喜欢
  • 2021-01-31
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多