转换html表

时间:2012-05-19 00:54:23

标签: php html

嗨我有一系列按字母顺序排列的电影名称,其中我想创建一个html表格,我想在运行中这样做,所以我做了以下内容:

echo "<div align=\"center\"><table>";   
$i=0;
foreach ($results as $entry){   
    //If first in row of 4, open row
    if($i == 0) {
        echo "<tr>\n";
    }
    //print a cell
    echo "\t<td>" . $entry . "</td>\n";
    i++;
    //if last cell in row of 4, close row
    if($i == 4) {
         echo "</tr>\n";
        $i=0;
    }
}

if($i < 4)  {
    while($i < 4) {
        echo "\t<td></td>\n";
        $i++;
    }
    echo "</tr>\n";
}
echo "</table></div>";

然而,这会构建一个表格,如下所示:

entry0 | entry1 | entry2 | entry3
entry4 | entry5 | entry6 | entry7

我怎样才能构建如下表格:

entry0 | entry3 | entry6
entry1 | entry4 | entry7
entry2 | entry5 | entry8

我猜我必须重新组织我的$ results数组并仍以相同的方式构建表?

我是非常新的PHP(一周!)所以我不确定如何去做这个

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

$results = array( 'e1', 'e2', 'e3', 'e4', 'e5', 'e6','e7' );

$NUM_COLUMNS = 3;

$numRows = count($results) / $NUM_COLUMNS;
if (count($results) % $NUM_COLUMNS > 0) {
  $numRows += 1;
}

echo "<div align=\"center\"><table>";
$i=0;
for ($i = 0; $i < $numRows; $i++) {
  echo "<tr>\n";

  $index = $i;
  for ($j = 0; $j < $NUM_COLUMNS; $j++) {
    //print a cell
    $entry = '';
    if ($index < count($results)) {
      $entry = $results[$index];
    }
    echo "\t<td>" . $entry . "</td>\n";

    $index += $numRows;
  }

  echo "</tr>\n";
}

echo "</table></div>";

这是经过测试的,包括垂直排序项目。我会写一个描述,但我接到一个电话,不得不去。如果你有~1小时内我会回答问题。 (对不起!)

答案 1 :(得分:0)

这个怎么样:(我没有测试,但应该没问题)

<?php
$i = 1;
$max = 3; // this is the number of columns to display

echo "<div align=\"center\"><table><tr>"; 

foreach ($results as $entry) {
    echo "<td style=\"text-align: center;\">";
    echo $entry;
    echo "</td>";

    $i++;

    if ($i == ($max)) {
        echo '</tr><tr>';

        $i = 1;
    }
}

echo "</tr>\n";
echo "</table></div>";
?>
相关问题