views:

43

answers:

3

I have an array of people's names:

Array
(
    [1] => A. Aitken
    [2] => A. C. Skinner
    [3] => A. Chen
    [4] => R. Baxter
)

What's the quickest way to sort the array in (alphabetical) order of the surname in php? i.e. to give

Array
(
    [1] => A. Aitken
    [4] => R. Baxter
    [3] => A. Chen
    [2] => A. C. Skinner
)
+3  A: 

Have a look at uksort and the example given there, which is very similar to your problem.

You may want to replace the regexps there with

preg_replace("/[A-Z]\\. /", '', $a);
mvds
Thanks - this works. For completeness you might just want to correct the typo in the pattern - I think it should be "@[A-Z]\\. @" (or "/[A-Z]\\. /").
Tomba
good point, corrected!
mvds
+4  A: 
function cmp($a, $b)
{
    $a1 = explode(' ', $a);
    $b1 = explode(' ', $b);
    return strcasecmp(end($a1), end($b1));
}

usort($arr, 'cmp');
Daniel Egeberg
+1  A: 
Kamil Szot
That gives a lot of `E_STRICT` warnings.
Daniel Egeberg
@Daniel Egeberg - thanks, I've fixed this by replacing end() with array_slice(,-1);
Kamil Szot