问题
I have an html table that is populated from a text file, formatted and semi colon separated. I would like the user to have the option of sorting alphabetically with either of the columns when clicking on the column name (header).
How do I do this in php?? Or is there another way of doing this? Thanks for your help.
Sample raw data/input looks like this:
TYPE=abc;PART=georgetown;FILE=goog_abc.dat.2010122211.gz
TYPE=xyz;PART=ucny;FILE=aol_xyz.dat.2010122209.gz
Php code for table:
$lines = preg_split('~\s*[\r\n]+\s*~', file_get_contents('/temp/tab.txt'));
foreach($lines as $i => $line) {
$pairs = explode(';', $line);
foreach($pairs as $pair) {
list($column, $value) = explode('=', $pair, 2);
$columns[$column] = true;
$rows[$i][$column] = $value;
}
}
$columns = array_keys($columns);
echo '<table><thead><tr>';
foreach($columns as $column) {
echo '<th>'.$column.'</th>';
}
echo '</tr></thead><tbody>';
foreach ($rows as $row) {
echo '<tr>';
foreach($columns as $column){
echo '<td>'.$row[$column].'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
回答1:
I'd recommend using some jQuery. In fact, this looks like exactly what you need.
Edit Put this in between your <head> tags
<script type="text/javascript">
$(document).ready(function()
{
$("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} );
}
);
</script>
Or you can put it in a separate file and link it like this. (Probably only do this if you intend to write more javascript.
<script type="text/javascript" src="path/to/file.js"></script>
回答2:
Use something javascript based to sort the table after you draw it. Trying to add this kind of sorting from within PHP is painful and not needed unless you have multiple pages of data (then you need PHP to sort it in the database side). Here is a list that gives you a LOT of options for sortable tables - you should be able to apply many of those to your table after you generate it using PHP.
http://www.webdesignbooth.com/15-great-jquery-plugins-for-better-table-manipulation/
来源:https://stackoverflow.com/questions/4522890/making-html-table-columns-optionally-sortable