How can I add a new row in a table every 10 columns automatically?

↘锁芯ラ 提交于 2019-12-13 10:55:09

问题


I have 2 queries that pull 2 different data set from the database first one contains the header for a table so if the total results are 10 then we have 10 headers to the table.

the second one will have records each with one value for each column. so if I have 5 records this means 5 x 10(total headers) = 50 records in the second dataset.

those 50 records I want to display it in the table.

My approach is to display one record at a time but after every 10 records close and open a new for the next row.

I am not sure if this is the best approach to this problem but I am open to better ideas.

Assuming my approach is a good approach, how can I create a new row in the table after every 10 records.

I have tried to acomplish this by using the Mod operation in PHP but this is not working for me.

Here is my current code that display data but it does not add at the correct time/place.

My question is how to add fix this code to display the results correctly?

    //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>';

回答1:


You can use modulus operation.

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


来源:https://stackoverflow.com/questions/17355623/how-can-i-add-a-line-after-every-10-records-using-mod

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!