【问题标题】:Single php array to html table单个php数组到html表
【发布时间】:2016-07-31 18:12:10
【问题描述】:

这个想法是从这个数组中打印一个 html 表格:

$arr = ['1','2','3','4,'5,'6','7','8','9'];

我希望我的桌子是这样的:

1 2 3

4 5 6

7 8 9

我尝试了很多,但我找不到这样做的想法。

我的想法是打破每三个元素,但我需要更聪明的东西。

【问题讨论】:

    标签: php html arrays html-table


    【解决方案1】:

    你可以像这样使用array-chunk

    $arr = ['1','2','3','4','5','6','7','8','9'];
    
    echo "<table>";
    foreach(array_chunk($arr, 3) as $row) {
        echo "<tr>";
        foreach($row as $cell) {
            echo "<td>$cell</td>";   
        }
        echo "</tr>";
    }
    echo "</table>";
    

    【讨论】:

      【解决方案2】:
      $arr = ['1','2','3','4','5','6','7','8','9'];
      
      $from=0; //index from of arr
      $number=3; //number cell per row
      echo "<table border='1'>";
      while($row=array_slice($arr,$from,$number)){
          echo "<tr>";
          foreach($row as $cell) {
              echo "<td>$cell</td>";   
          }
          echo "</tr>";
          $from+=$number;
      }
      echo "</table>";
      

      【讨论】:

        【解决方案3】:
        <?php
        $arr = ['1','2','3','4','5','6','7','8','9'];
        print "<table>\n";
        foreach(array_chunk($arr, 3) as $row) {
                print "<tr>";
                foreach($row as $col) {
                        print "<td>";
                        print $col;
                        print "</td>";
                }   
                print "</tr>\n";
        }
        print "</table>";
        ?>
        

        【讨论】:

          猜你喜欢
          • 2014-11-30
          • 2016-04-12
          • 2012-01-16
          • 2017-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多