I have an array. eg:
names = {
'John Doe',
'Tom Watkins',
'Jeremy Lee Jone',
'Chris Adrian'
}
And I want to order it alphabetically by last name(last word in string). Can this be done?
I have an array. eg:
names = {
'John Doe',
'Tom Watkins',
'Jeremy Lee Jone',
'Chris Adrian'
}
And I want to order it alphabetically by last name(last word in string). Can this be done?
$names = array(
'John Doe',
'Tom Watkins',
'Jeremy Lee Jone',
'Chris Adrian',
);
usort($names, function($a, $b) {
$a = substr(strrchr($a, ' '), 1);
$b = substr(strrchr($b, ' '), 1);
return strcmp($a, $b);
});
var_dump($names);
Online demo: http://ideone.com/jC8Sgx
You can use the custom sorting function called usort (http://php.net/manual/en/function.usort.php). This allows you create a comparison function which you specify.
So, you create a function like so...
function get_last_name($name) {
return substr($name, strrpos($name, ' ') + 1);
}
function last_name_compare($a, $b) {
return strcmp(get_last_name($a), get_last_name($b));
}
and you make the ultimate sort using usort using this function:
usort($your_array, "last_name_compare");
The first function you'd like to look at is sort.
Next, explode.
$newarray = {};
foreach ($names as $i => $v) {
$data = explode(' ', $v);
$datae = count($data);
$last_word = $data[$datae];
$newarray[$i] = $last_word;
}
sort($newarray);
There comes another approach:
<?php
// This approach reverses the values of the arrays an then make the sort...
// Also, this: {} doesn't create an array, while [] does =)
$names = [
'John Doe',
'Tom Watkins',
'Jeremy Lee Jone',
'Chris Adrian'
];
foreach ($names as $thisName) {
$nameSlices = explode(" ", $thisName);
$sortedNames[] = implode(" ", array_reverse($nameSlices));
}
$names = sort($sortedNames);
print_r($sortedNames);
?>