格式化循环php的结果

时间:2013-07-01 09:01:50

标签: php

我坚持用4列制作一个表格,表格的数据来自一个数组,这是我做过的代码:

$sample // this is an array and it has 15 values inside
<table>
foreach($sample as $x){
$rows="<td>$x</td>".$rows;
$l++;
if($l==4){
echo"<tr>".$rows."</tr>";
$l=0;
$rows="";
}
}
</table>

如果我是正确的,这段代码将生成一个3行和4列的表格,缺少的内容是我需要包含$ sample中的所有数据我需要这种代码的输出。

[1][1][1][1]
[1][1][1][1]
[1][1][1][1]
[1][1][1][0]

1是$ sample的数组值,而零没有值,因为值og $ sample只有15

1 个答案:

答案 0 :(得分:0)

试试这个:

<?php
    echo "<table border='1'>";
    $sample = array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15");          #with 15 rows
    echo "<tr>";
    $key   = 1; 
    foreach($sample as $each){
        if( ($key%4) == 0){
            echo "<td>{$each}</td></tr><tr>";
        }else{
            echo "<td>{$each}</td>";
        }
        $key++;
    }
    echo "</table>";
?>