嗨,昨晚有人通过另一个问题帮助我编写了一些代码:转换 html 表
我对它进行了一些更改,但我又有点卡住了。
基本上$results是一系列电影。我已经格式化了它,以便在数组中的第一个字母发生变化时包含一个单独的条目,其中包含第一个字母。
这是执行此操作的代码:
while (false !== ($entry = readdir($handle)) ) {
if($entry == "." or $entry == "..")
continue;
if($i == 0) {
array_push($results,substr($entry, 0,1));
} else if (substr($entry, 0,1) != substr($lastEntry, 0,1)) {
array_push($results,substr($entry, 0,1));
}
$lastEntry = $entry;
array_push($results,$entry);
$i++;
}
这将产生如下所示的数组:
Array (
[0] => 0
[1] => 007, A View to a Kill (1985)
[2] => 1
[3] => 127 Hours (2010)
[4] => A
[5] => A Clockwork Orange (1971)
[6] => B
[7] => Back to the Future (1985)
[8] => Butterfly on a Wheel (2007)
[9] => C
[10] => Carnage (2011)
[11] => Casino (1995)
[12] => D
[13] => Defiance (2008)
)
所以基本上我想生成一个表,它为每个索引(0,1,A,C等(一个不同的CSS类,并给它一个2的行跨度。我已经做到了。我制作了一个看起来正确的表格。下面的代码在添加一个 rowspan=2 的单元格时$indexRow递增,然后下一行打印了 number_of_cols - $indexRow。由于上行中的 rowspan=2 单元格占据了当前行中的一个单元格。
$NUM_COLUMNS = 3;
$numRows = count($results) / $NUM_COLUMNS;
if (count($results) % $NUM_COLUMNS > 0) {
$numRows += 1;
}
echo "<div align='"center'"><table>";
$i=0;
$indexRow=0;
for ($i = 0; $i < $numRows; $i++) {
echo "<tr>'n";
$index = $i;
$j=0;
if($indexRow > 0) {
$j+=$indexRow;
$indexRow=0;
}
while ($j < $NUM_COLUMNS) {
$entry = '';
if ($index < count($results)) {
$entry = $results[$index];
}
if(strlen($entry) < 2) {
echo "'t<td rowspan='"2'" class='"movieindex'">" . $entry . "</td>'n";
$indexRow++;
} else {
echo "'t<td>" . $entry . "</td>'n";
}
$index += $numRows;
$j++;
}
echo "</tr>'n";
}
echo "</table></div>";
我的实际问题是电影现在没有正确排序,行跨度 = 2 个单元格。电影应该垂直排序,但会被索引单元格抛弃。我不确定我如何规避这一点,有什么想法吗?
这是我得到的表格:
<div align="center">
<table>
<tr>
<td rowspan="2" class="movieindex">0</td>
<td>Hancock (2008)</td>
<td>Sin City (2005)</td>
</tr>
<tr>
<td>007, A View to a Kill (1985)</td>
<td>Hangover (2009)</td>
</tr>
<tr>
<td>007, Diamonds Are Forever (1971)</td>
<td>Happy Feet Two (2011)</td>
<td>Snow White (1987)</td>
</tr>
这就是我想要的:
<div align="center">
<table>
<tr>
<td rowspan="2" class="movieindex">0</td>
<td>Hancock (2008)</td>
<td>Sin City (2005)</td>
</tr>
<tr>
<td>Hangover (2009)</td>
<td>Snow White (1987)</td>
</tr>
<tr>
<td>007, A View to a Kill (1985)</td>
<td>Happy Feet Two (2011)</td>
<td>Step Brothers (2008)</td>
</tr>
如果需要更多解释,请询问,我会编辑。基本上我要问的是我如何正确垂直排列单元格?
也许这会帮助你理解我想做什么:http://imageshack.us/f/163/exampletable.png/
正如我在评论中所说,作为一个肮脏的解决方案,您可以在索引之后在数组中添加一个占位符,并且不要在代码中显示它们。
} else if (substr($entry, 0,1) != substr($lastEntry, 0,1)) {
array_push($results,substr($entry, 0,1));
array_push($results,"");
}
这将导致如下数组:
Array (
[0] => 0
[1] =>
[2] => 007, A View to a Kill (1985)
[3] => 1
[4] =>
[5] => 127 Hours (2010)
);
如果将代码修改为以下内容:
if(strlen($entry) == 1) {
echo "'t<td rowspan='"2'" class='"movieindex'">" . $entry . "</td>'n";
$indexRow++; // This might be unneeded now, did not test this myself
} else if(strlen($entry) == 0){
// Do nothing, just a placeholder
} else {
echo "'t<td>" . $entry . "</td>'n";
}