从数组中的值创建4列表

时间:2014-11-18 22:59:25

标签: php html arrays html-table

你有阵列:
$ tab = [1,2,3,4,5,6,7,8,9];

我想使用数组标签中的值制作表格 表必须是最多4列 它看起来应该是这样的:

1 2 3 4
5 6 7 8
9

我的示例代码(不工作):

$tab = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$max = count($tab);

// 1 FOR - ROWS
echo "<table>";
    for ( $i = 0; $i < $max; $i+=4 )
    {
    echo "<tr>";
        // 2 FOR - COLUMNS
        for ( $x = $i; $x < 4; $x++ ) //our array is 9-elemented, in third row $x going to be out of index
        {
            printf('<td>%s</td>', $tab[$x]);
        }
    echo "</tr>";
    }
echo "</table>";

4 个答案:

答案 0 :(得分:2)

<?php
    $tab = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    $i=1;
    echo '<table>'
    foreach($tab as $key => $val){
        if ($i==1) echo '<tr>'
        if($i%4==0){ $i=0; echo "<td>$val</td> </tr>";}
        else {
          echo "<td> $val </td>";
        }
        $i++
    }
    echo '</table>'
?>

答案 1 :(得分:1)

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$chunks = array_chunk($arr, 4);
echo '<table>';
foreach ($chunks as $chunk) {
    echo '<tr>';
    foreach ($chunk as $val) {
        printf('<td>%s</td>', $val);
    }
    echo '</tr>';
}
echo '</table>';

答案 2 :(得分:1)

$tab = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$max = count($tab);

echo "<table>";
    echo "<tr>";
    for ( $i = 0; $i < $max; $i++ ) {
        if ($i > 0 && $i % 4 == 0) {
            echo "</tr><tr>";
        }
        printf('<td>%s</td>', $tab[$i]);
    }
    echo "</tr>";
echo "</table>";

答案 3 :(得分:1)

$tab = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$max = count($tab);
echo "<table>";
    for($i=0;$i<$max;$i=$i+4){
        echo '<tr>';
            for($x=0;$x<4;$x++){
                if($x+$i>=$max){
                    continue;
                }else{
                    echo '<td>'.$tab[($x+$i)].'</td>';
                }
            }
        echo '</tr>';
    }
echo "</table>";