大家好,我有一个按字母顺序排列的电影名称数组,我想创建其中的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的新手(一周!)所以我真的不知道该怎么做
谢谢你的帮忙
发布于 2012-05-19 09:19:37
$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小时内有任何问题,我将回答您的问题。(对不起!)
发布于 2012-05-19 09:05:40
这个怎么样:(我没有测试,但应该没问题)
<?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>";
?>
https://stackoverflow.com/questions/10661452
复制相似问题