making html table columns optionally sortable

左心房为你撑大大i 提交于 2019-12-10 12:18:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!