Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

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

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>';
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use modulus operation.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...