单个php数组到html表


Single php array to html table

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

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

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

1 2 3
4 5 6
7 8 9

我试了很多,但都找不到这样做的主意。

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

您可以这样使用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>";
$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>";
<?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>";
?>