PaulWill
PaulWill

Reputation: 623

Sort text file by using last name

I have a php little script that sorts the data from a text file by using the first name but I need to sort by last name, the text file looks like this

name1,last1,email1
name2,last2,email2
name3,last3,email3

how can I sort the text file by using last name?

$data = file($file_path);
natsort($data);
file_put_contents($new_file_path, implode("\n", $data));

Upvotes: 1

Views: 380

Answers (2)

slapyo
slapyo

Reputation: 2991

Grab the 2nd column, put it in an array and sort it. Then using the key from the newly sorted array build the result and save it to the new file.

$rows = array();
$result = '';
$data = file($data_path);

foreach($data as $key => $val) {
    $rowarray = explode(",", $val);
    $rows[] = $rowarray[1];
}

asort($rows);

foreach($rows as $key => $val) {
    $result .= trim($data[$key]) . "\r\n";
}

file_put_contents($new_file_path, $resultstring);

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227270

If you only want to sort on one field, then you need to split on the ',' and use usort.

$data = file($file_path);
usort($data, function($a, $b){
    $a = explode(',', $a);
    $b = explode(',', $b);

    return strnatcmp($a[1], $b[1]);
});
file_put_contents($new_file_path, implode("\n", $data));

Upvotes: 0

Related Questions