【发布时间】:2016-02-24 22:50:42
【问题描述】:
我有一个包含如下(虚拟)数据的 CSV 文件:
Mike Judge, Office Space, Comedy
Larry Wachowski, Matrix Zero, Action
Sofia Coppola, Lost In Translation, Drama
Ron Howard, A Beautiful Mind, Drama
Joe Biden, Your Big Hat, Sports
Barack Obama, The Stubborn Goat, Drama
Steve Smith, 2 Beautiful Ants, Suspense
Jared Hess, Napoleon Dynamite, Comedy
Jack Daniels, Field of Dreams, Drama
我需要按姓氏字母顺序排序的第一个字段。这行得通。
然后我需要在 HTML 表格中显示数组,并且能够将列数设置为 5。我需要每个单元格保存 CSV 文件中的一行,然后从左向右移动以填充表格。
我尝试过的一切都让我快到了,但表格无法正确显示 - 它缺少 td 标记或最后一个 td 中没有  。
任何帮助将不胜感激。
这是我目前所拥有的:
$file = fopen("dummy-list.csv", "r") or die('cannot open file');
// sort
$surnames = array();
$rows = array();
//build array of surnames, and array of rows
while (false != ( $row = fgetcsv($file, 0, ',') )) {
//extract surname from the first column
//this should match the last word before the comma, if there is a comma
preg_match('~([^\s]+)(?:,.*)?$~', $row[0], $m);
$surnames[] = $m[1];
$rows[] = $row;
}
//fclose($file);
//sort array of rows by surname using our array of surnames
array_multisort($surnames, $rows);
//print_r($rows);
// set # of table columns
$numCols = 4;
$i=0;
echo '<table border="1" align="center"><tr>' . "\n";
foreach( $rows as $rows2 )
{
if ($i % $numCols == 0 && $i != 0)
echo "</tr>\n<tr>"; // every time but the first
echo '<td>';
foreach( $rows2 as $key )
{
echo $key . '<br />';
$i++;
}
echo "</td>\n";
}
while ($i++ % $numCols != 0)
echo '<td> </td>' . "\n"; // fill in empty cells
// end table
echo '</tr></table>' . "\n\n\n";
【问题讨论】:
-
我通过将 CSV 转换为 JSON 并为此使用 DataTables 来实现这一点
-
这是我们在 1998 年使用的表格。
-
你有例子吗?
-
GolezTrol - 你的评论没有帮助,除非你要推荐你现在在 2016 年使用的东西......
标签: php html csv html-table