I have an array as follows:
Array(
[27] => 'Sarah Green',
[29] => 'Adam Brown',
[68] => 'Fred Able'
);
I'd like to sort it by surname and preserve the keys:
Array(
[68] => 'Fred Able'
[29] => 'Adam Brown',
[27] => 'Sarah Green'
);
Some names may have more than two first names, but it's always the very last name I want to sort on.
What would be the best way to do this in PHP?
The ksort() function sorts an associative array in ascending order, according to the key. Tip: Use the krsort() function to sort an associative array in descending order, according to the key. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.
Explanation: The function sort() will sort the arrays in ascending order, the function rsort() will sort arrays in descending order. While the function asort() will sort associative arrays in ascending order, according to the value.
You can use the uasort
function, which allows you to specify a custom sorting method while also preserving keys:
<?php
// A function to sort by last name.
function lastNameSort($a, $b) {
$aLast = end(explode(' ', $a));
$bLast = end(explode(' ', $b));
return strcasecmp($aLast, $bLast);
}
// The array of data.
$array = array(
27 => 'Sarah Green',
29 => 'Adam Brown',
68 => 'Fred Able'
);
// Perform the sort:
uasort($array, 'lastNameSort');
// Print the result:
print_r($array);
?>
Here's a demo.
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