本文介绍了嵌套PHP while循环以创建一个动态表,该表每行2行,每行5列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的代码如下:

<?php

$i = 6; //will be pulled from a database
if ($i != "10") {
$countb = (10-$i);

}
echo "<table border=\"1\" align=\"left\">";
echo "<tr><th>Results</th>";
echo "</tr>";
while ( $i != 0) {
    echo "<tr><td>";
    echo "Good";
    echo "</td>";
    $i= $i- 1;
}
while ( $countb != 0) {
    echo "<tr><td>";
    echo "not good";
    echo "</td>";
    $countb= $countb- 1;
    }
echo "</table>";
?> 

这将创建一个1列10行表.我想要两行,每行5列.基本上,如果用户没有10个好标记,我想用不合格的商品来填写缺失的商品.

This creates a 1 column 10 row table. I want to have two rows and 5 columns per row. Basically, if the user does not have 10 good marks I want to fill in the missing goods with not good.

推荐答案

我认为可以对此进行简化,语义上的改进,并且可以更灵活地扩展以使用任何可能的得分并保持5 col格式.

I think this could be simplified, semantically improved, and more flexibly extended to use any possible score and stay with the 5 col format.

<?php
// this is the total possible score
$possibleScore = 10;

// this is the actual score
$i = 6; //will be pulled from a database

// semantically complete html table
echo "
<table border='1' align='left'>
  <thead>
    <tr><th>Results</th></tr>
  </thead>
  <tbody>
    <tr>";

// rate every step from zero to total possible score
for ($ix=0;$ix<$possibleScore;$ix++) {

  // new row every 5 cols, but not first row
  if ($ix !== 0 && $ix % 5 === 0)
    echo "</tr>\n    <tr>";

  // good if index less than score
  if($ix<$i)
    echo "<td>Good</td>";
  else
    echo "<td>not good</td>";
}

echo "</tr>
  </tbody>
</table>
";

输出结果:

<table border='1' align='left'>
  <thead>
    <tr><th>Results</th></tr>
  </thead>
  <tbody>
    <tr><td>Good</td><td>Good</td><td>Good</td><td>Good</td><td>Good</td></tr>
    <tr><td>Good</td><td>not good</td><td>not good</td><td>not good</td><td>not good</td></tr>
  </tbody>
</table>

但是现在您可以随意用任何值代替总分和实际分,同时仍保持报告率.

But now you're free to substitute any values in for total score and actual score while still maintaining the reporting ratio.

// this is the total possible score
$possibleScore = 18;

// this is the actual score
$i = 11; //will be pulled from a database

结果:

<table border='1' align='left'>
  <thead>
    <tr><th>Results</th></tr>
  </thead>
  <tbody>
    <tr><td>Good</td><td>Good</td><td>Good</td><td>Good</td><td>Good</td></tr>
    <tr><td>Good</td><td>Good</td><td>Good</td><td>Good</td><td>Good</td></tr>
    <tr><td>Good</td><td>not good</td><td>not good</td><td>not good</td><td>not good</td></tr>
    <tr><td>not good</td><td>not good</td><td>not good</td></tr>
  </tbody>
</table>

这篇关于嵌套PHP while循环以创建一个动态表,该表每行2行,每行5列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 22:25