Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array of names by surname preserving the keys

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?

like image 691
Simon Blackbourn Avatar asked Feb 21 '12 00:02

Simon Blackbourn


People also ask

How do you sort an array by key?

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.

Which function is used to sort array in ascending?

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.


1 Answers

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.

like image 123
Ry- Avatar answered Nov 09 '22 15:11

Ry-