How would I sort the following CSV file using PHP? I would like to sort by last name. Do I use regex somehow to get the first letter in the last name? Any help is appreciated
Here is an excerpt of my CSV file - with a ";" delimiter between names and addresses
John C. Buckley, M.D.;123 Main Street, Bethesda MD 20816
Steven P. Wood;345 Elm Street, Rockville, MD 20808
Richard E. Barr-Fernandez;234 Pine Street, Takoma Park MD 20820
Charles Andrew Powell; 678 Oak Street, Gaithersburg MD 20800
Mark David Horowitz, III; 987 Wall Street, Silver Spring MD 20856
Here is my attempt. I'm not sure how robust the regex is to extract the surname though.
<?php
$handle = fopen('c:/csv.txt', 'r') or die('cannot read file');
$surnames = array();
$rows = array();
//build array of surnames, and array of rows
while (false != ( $row = fgetcsv($handle, 0, ';') )) {
//extract surname from the first column
//this should match the last word before the comma, if there is a comma
preg_match('~([^\s]+)(?:,.*)?$~', $row[0], $m);
$surnames[] = $m[1];
$rows[] = $row;
}
fclose($handle);
//sort array of rows by surname using our array of surnames
array_multisort($surnames, $rows);
print_r($rows);
//you could write $rows back to a file here if you wanted.
Edit
I just realised that you don't really need to strip off the peoples' suffixes, because this probably won't really affect sorting. You could just split the first column on space and take the last one (as karim79 suggested). This might break though if the person has more suffixes with spaces, so I'll leave my answer intact.
Well, because it is a CSV
$lines = file($file);
foreach($lines as $line)
{
$parts = explode(";", $line);
$last = explode(" ", $parts[0]);
$last = end($last);
$array[$last] = $parts;
}
ksort($array);
// ..... write it back to file
The PHP function array_multisort should do what you want. You'll need to read the CSV into a multi-dimensional array - see the third example on the linked page.