问题
My current code looks like this:
<?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>";
?>
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.
回答1:
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>
";
Results in this output:
<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
Results in this:
<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>
回答2:
I am not sure what you want, but do you want something like this?
<?php
$d = 6; //will be pulled from a database
$i=10;
$c=$i; //c is 10
if ($d != $i) {
$countb = (10-$d);
}
echo "<table border=\"1\" align=\"left\">";
echo "<tr><th>Results</th>";
echo "</tr><tr>";
while ( $i != 0) {
if($i>$countb){
echo "<td>";
echo "Good";
echo "</td>";
}
if($i==($c/2)+1){
echo "</tr>";
}
if($i<=$countb){
echo "<td>";
echo "not good";
echo "</td>";
}
$i=$i-1;
}
echo "</tr></table>";
?>
来源:https://stackoverflow.com/questions/37637905/nested-php-while-loop-to-create-a-dynamic-table-that-is-2-rows-by-5-columns-per