Dynamic table (colons depend on the content of the table)

天涯浪子 提交于 2019-12-12 02:39:02

问题


This php code shows me the content of a directory on my website:

<?php
 $dir = opendir(getcwd());
 ?>
<body>
<table>
    <tbody>
        <tr>
<?php
  while (($file = readdir($dir)) !== false) {
      {
            echo "<td>". $file ."</td>";
    }       
  }
  closedir($dir);
?>
        </tr>
    </tbody>
</table>
</body>

It puts the results in a table. The problem is that the PHP code generates a <td> tag and store the results in it. So the final table has one <tr> and as many <td> tags as there are results.

What I want to have is a table with 3 columns (3 td) per each line (tr tag).

Is there a way to make the table dynamic and for each third <td> tag turns to be a <tr> tag so the results look like this: (click here)

Instead of looking like this: (click here)


回答1:


try this:

<?php
 $dir = opendir(getcwd());
 ?>
<body>
<table>
    <tbody>

<?php
  $n = 0;
  while (($file = readdir($dir)) !== false) {
      {
           if($n%3 == 0){echo "<tr>";}
           echo "<td>". $file ."</td>";
           $n++;
    }       
  }
  closedir($dir);
?>

</tbody>




回答2:


you can use modulus to keep track of where you are in the loop. Then, when you've hit a multiplication of 3, you restart the table row:

<?php
   $dir = opendir(getcwd());
?>
<body>

    <table>
        <tbody>
            <tr>
            <?php
                $counter = 0;
                while (($file = readdir($dir)) !== false) {
                    {
                        if($counter % 3 == 0 && $counter != 0) echo "</tr><tr>";
                        echo "<td>". $file ."</td>";
                        $counter++;
                    }       
                }
                closedir($dir);
            ?>
            </tr>
       </tbody>
    </table>

</body>


来源:https://stackoverflow.com/questions/12799053/dynamic-table-colons-depend-on-the-content-of-the-table

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