foreach加上在php中

时间:2011-12-17 06:29:18

标签: php for-loop foreach

我想做:

aaa | bbb | ccc | ddd  etc
1   |  1  |  1  | 1 
2   |  2  |  2  | 2 
3   |  3  |  3  | 3
etc

对于aaa,bbb等我使用FOREACH

<table><tr>
foreach ($data as $d){
echo "<td>" . $d . "</td>";
}
</tr>

for ($i = 0; $i < 20; $i++){
 echo "<tr><td>" . $i . "</td></tr>";
}

但这工作不好。我怎样才能为来自foreach的所有数据使用循环FOR?

2 个答案:

答案 0 :(得分:2)

我认为你可以像这样生成你的表:

$columns = array('aaa','bbb','ccc','ddd');
$num_cols = count($columns);
echo "<table>";
echo "<tr>";
foreach($columns as $col)
{
   echo "<td>$col</td>";
}
echo "</tr>";

for($i=1;$i<20;$i++)
{
    echo "<tr>";
    for($j=0;$j<$num_cols;$j++)
    {
      echo "<td>$i</td>";
    }
    echo "</tr>";
 }

echo "</table>";

答案 1 :(得分:2)

一般取决于$data的样子。

<?php

$data = array('aaa', 'bbb', 'ccc', 'ddd'); // Assuming that $data is a columns storage
$rows = 10; // $rows = count($data); if you wish to have same number of columns and rows

echo '<table>';
echo '<tr>';
foreach ($data AS $item)
{
    echo '<td>' . $item . '</td>';
}
echo '</tr>';
for ($idx = 0; $idx < $rows; $idx++)
{
    echo '<tr>';
    for ($col = 1, $col_num = count($data); $col <= $col_num; $col++)
    {
        echo '<td>' . $idx . '</td>';
    }
    echo '</tr>';
}
echo '</table>';

?>

P.S。尚未测试代码。