我一直在研究这个简单的代码,它将CSV文件放入一个漂亮的表中。但由于数据是导入的,因此设置ODD行是一件非常困难的事情。
我需要的只是解决某些行的方法,因此我可以像背景一样制作“斑马”,并将特定数据放在另一种文本样式中。
aynone有想法吗?非常感谢!
<?php
print("<TABLE>\n");
$row = 0;
$handle = fopen("test_file.csv", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c <= $row; $c++)
{
print("<TR>");
print("<TD>".$data[0]." </td>");
print("<TD>".$data[1]." </td>");
print("<TD>".$data[2]." </td>");
print("<TD>".$data[3]." </td>");
print("<TD>".$data[4]." </td>");
print("</TR>");
}
}
fclose($handle);
?>
答案 0 :(得分:1)
怎么样
print("<TR class='" . ($c%2 == 0?'even':'odd')."'>");
之后可以添加正确的CSS
.even {
background-color: #aaaaaa;
}
.odd {
background-color: #fffff;
}
答案 1 :(得分:1)
使用类似:
<table>
<tbody>
<?php
$row = 0;
$handle = fopen('test_file.csv', 'r');
while ($data = fgetcsv($handle, 1000, ',')):
$class = ++$row & 1 == 1 ? ' class="odd"' : '';
$num = count($data);
?>
<tr<?php echo $class; ?>>
<?php for ($c=0; $c <= $num; $c++) {
<td><?php echo $data[$c]; ?></td>
<?php endfor; ?>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<?php fclose($handle); ?>
使用:
tr.odd td { background: #CCC; }
或使用短标签(我个人更喜欢):
<table>
<tbody>
<?
$row = 0;
$handle = fopen('test_file.csv', 'r');
while ($data = fgetcsv($handle, 1000, ',')):
$class = ++$row & 1 == 1 ? ' class="odd"' : '';
$num = count($data);
?>
<tr<?= $class ?>>
<? for ($c=0; $c <= $num; $c++) {
<td><?= $data[$c]; ?></td>
<? endfor; ?>
</tr>
<? endwhile; ?>
</tbody>
</table>
<? fclose($handle); ?>
答案 2 :(得分:1)
有一个名为jQuery的TableSorter插件允许斑马式着色,还增加了点击排序行的功能。它很容易集成。
这不是一个纯粹的PHP解决方案,但在大多数情况下,你最终还是要编写CSS和JavaScript代码,所以这最终会节省大量时间并阻止你对这些东西进行硬编码进入你的PHP逻辑。
首先,您要链接文档的<head>
中的脚本:
<script type="text/javascript" src="/path/to/jquery-latest.js"></script>
<script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script>
然后确保您的表格包含<thead>
和<tbody>
元素:
<table id="myTable">
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Email</th>
<th>Due</th>
<th>Web Site</th>
</tr>
</thead>
<tbody>
<tr>
<td>...
...
</tbody>
</table>
结束然后你用jQuery启用它:
$(document).ready(function()
{
$("#myTable").tablesorter({ widgets: ['zebra'] });
}
);