0

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

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

I saw this. Thanks. I'm testing it now. I got the table data example to show in table format, but not able to get the sorting function to work. I've never used jQuery before. So, I must be placing the call incorrectly. Where do I put the java script document call? At the beginning? outside the <html></html> brackets?
1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.