Forum Moderators: coopster

Message Too Old, No Replies

Sorting fgetcsv information

sorting fgetcsv

         

cookie2

9:49 pm on Jan 29, 2004 (gmt 0)

10+ Year Member



I have a CSV text file called alumni.txt that is set up like so:

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.

coopster

10:22 pm on Jan 29, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, cookie2!

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

Then call it after you've closed the file handle, before you do any processing of the array:

fclose($id);
usort($table, "cmp");
echo "<table>\n";

The link provided will give you details on how it works.

coopster

10:31 pm on Jan 29, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Note:
You may also want to use array_shift [php.net] to get the column headings out of the way first, before you sort. Then array_pop [php.net] to put them back on!

fclose($id);
$col_hdgs = array_shift($table);
usort($table, "cmp");
array_unshift($table, $col_hdgs);
echo "<table>\n";

cookie2

11:35 pm on Jan 29, 2004 (gmt 0)

10+ Year Member



Thank you coopster. No wonder I couldn't get it to work using sort. I will have to check out that array shift thing as that's a brand new one on me. I appreciate your answers and accompanying explanation. Now it makes sense.

coopster

12:08 am on Jan 30, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Oh, you're more than welcome, my friend. That's why we're here ;)