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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With