开发者

Styling rows in table that uses CSV data through PHP

I've been working on this simple code that puts a CSV file into a nice table. But because the data is imported, styling ODD rows is a pretty hard thing to do.

All I need would be a method to address certain rows, so I can make a "zebra" like background, and put specific data in another text style.

Does aynone have an idea? thanks a lot!

<?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]." &l开发者_高级运维t;/td>");
    print("<TD>".$data[3]." </td>");
    print("<TD>".$data[4]." </td>");
    print("</TR>"); 
}
}
fclose($handle);

?>


There is a jQuery plugin called TableSorter that allows for the zebra-style coloring and also adds the ability to to click-to-sort rows. It is very easy to integrate.

This is not a pure PHP solution, but in the majority of cases you're going to end up having to code CSS and JavaScript anyways, so this ends up saving a lot of time and prevents you from hard-coding that stuff into your PHP logic.

First you link the scripts in the <head> of your document:

<script type="text/javascript" src="/path/to/jquery-latest.js"></script> 
<script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script> 

Then you make sure your table has <thead> and <tbody> elements:

<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>

End then you enable it with jQuery:

$(document).ready(function() 
    { 
        $("#myTable").tablesorter({ widgets: ['zebra'] }); 
    } 
);


what about

print("<TR class='" . ($c%2 == 0?'even':'odd')."'>");

after you can add the proper CSS

.even {
  background-color: #aaaaaa; 
}

.odd {
  background-color: #fffff; 
}


Use something like:

<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); ?>

with:

tr.odd td { background: #CCC; }

Or with short tags (which I personally prefer):

<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); ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜