将表拆分为三行

时间:2014-03-18 16:17:02

标签: php html-table

我有一个PHP页面,其中一些是这样的:

if(mysql_num_rows($raw_results) > 0){ 

    echo "<table border='1'>
<tr>
<th>C1</th>
</tr>";

while($row = mysql_fetch_array($raw_results))
{
echo "<tr>";
echo "<td>" . $row['C1'] . "</td>";
echo "</tr>";
}
echo "</table>";

如何更改此表以使表格进入C1 C1 C1?

所以,如果我有以下一组值 - 1 2 3 4 5 6 7 8 9 - 该表返回以下内容

C1 C1 C1

1 2 3

4 5 6

7 8 9

我该怎么做?

6 个答案:

答案 0 :(得分:1)

类似的东西:

$cpt=1;
echo "<tr>";
while($row = mysql_fetch_array($raw_results))
{
  echo "<td>" . $row['C1'] . "</td>";
  if ($cpt%3==0)
    echo "</tr><tr>";
  $cpt++;
}
echo "</tr>";

将在每3个结果后创建一个新行

答案 1 :(得分:1)

$N中定义您想要的cols数量。

$N=3;
$col=0;
while($row = mysql_fetch_array($raw_results))
{
    $col++;
    if ($col==1) echo "<tr>";
    echo "<td>" . $row['C1'] . "</td>";
    if ($col==$N)
    {
        $col=0;
        echo "</tr>";
    }
}
if ($col>0) //if there is an open <tr>...
    echo "</tr>";

答案 2 :(得分:1)

if(mysql_num_rows($raw_results) > 0) { 
  echo "<table border='1'>
  <tr><th>C1</th><th>C1</th><th>C1</th></tr>";

  $col = 0;
  while($row = mysql_fetch_array($raw_results)) {
    if ($col == 0) { echo "<tr>"; }
    echo "<td>" . $row['C1'] . "</td>";
    if ($col == 2) { echo "</tr>"; }
    $col = ($col + 1) % 3
  }
  echo "</table>";
}

答案 3 :(得分:1)

这也是工作(有点短)

$a=1;
while($row = mysql_fetch_array($raw_results))
{
echo "<td>".$row['c1']."</td>".(($a%3==0)?'</tr><tr>':'');
$a++;
}

答案 4 :(得分:0)

将其更改为

if(mysql_num_rows($raw_results) > 0){ 
  echo "<table border='1'>
  <tr>
     <th>C1</th><th>C1</th><th>C1</th>";

$x = 0;
while($row = mysql_fetch_array($raw_results))
{
   if ($x % 3 == 0) {
     echo "</tr><tr>";
   }
   echo "<td>" . $row['C1'] . "</td>";
   $x++;
}
echo "</table>";

我假设您只有3列,结果的计数是3的子数 注意</tr><tr>

答案 5 :(得分:0)

没有测试,所以它可能是一些语法错误,但您可以这样做:

if(mysql_num_rows($raw_results) > 0){ 
    echo "<table border='1'>
    <tr>
    <th>C1</th>
    <th>C1</th>
    <th>C1</th>
    </tr><tr>";
    $i = 0;
    while($row = mysql_fetch_array($raw_results))
    {
        if ($i == 2) {
            $i = 0;
            echo "</tr>";
            echo "<tr>";
        }
        echo "<td>" . $row['C1'] . "</td>";
        $i++;
    }
    if ($i > 0) {
        echo "</tr>";
    }
    echo "</table>";