Forum Moderators: coopster
firstname;lastname;email;dates;
John;Smith;123@abc.com;1996 - Lifeguard in pool
Harry;Jones;tryme@who.com;1989 - Camp Counselor
Perry;White;fake@hotmail.com;1970 - Swim Team
Albert;Hall;noemail@nowhere.com;1967 - Leader
I can read this file into an HTML table just fine using fgetcsv using the following:
<?php
$filename = "alumni.txt";
$id = fopen($filename, "r");
while ($data = fgetcsv($id, filesize($filename),";"))
$table[] = $data;
fclose($id);
echo "<table>\n";
foreach($table as $row)
{
echo "<tr>";
foreach($row as $data)
echo "<td>$data</td>";
echo "</tr>\n";
}
echo "</table>\n";
?>
But what I need to do and cannot find the correct way is to sort the table on the second column ("lastname") so the lastnames are arranged from from A-Z. Can anyone help me figure out what I need to do with the sort function to get it to sort on the lastnames? Thanks.
PHP's usort [php.net] will allow you to sort an array by values using a user-defined comparison function:
function cmp($a, $b) {
// This will make it sort on the second index of the array;
// remember, arrays start with zero (0)!
$column_to_sort_on = 1;
if ($a[$column_to_sort_on] == $b[$column_to_sort_on]) return 0;
return ($a[$column_to_sort_on] < $b[$column_to_sort_on])? -1 : 1;
}
fclose($id);
usort($table, "cmp");
echo "<table>\n";
fclose($id);
$col_hdgs = array_shift($table);
usort($table, "cmp");
array_unshift($table, $col_hdgs);
echo "<table>\n";