0

I have an initial array with names and ID-s that have to be sorted, based on family names while following the local alphabet:

$names = array(
    "134" =>    "Mati Vänt",
    "24" =>     "Mati Vint",
    "11" =>     "Mati Wint",
    "12" =>     "John Zareem",
);

and the function to sort them (big thanks to Alma Do):

setlocale(LC_ALL, 'et_EE.utf8');
uasort($nimed, function($x, $y)
{
    return strcoll(
    end(preg_split('/\s+/', $x)),
    end(preg_split('/\s+/', $y))
);
});

Which gives the result: John Zareem, Mati Vint, Mati Wint, Mati Vänt.

It is correct in the sense that Z comes before V like in the local alphabet, but why are family names starting with one letter (V) mixed with names with a different first letter (W)? Is there perhaps a way to avoid it? Thanks in advance!

4
  • I don't know anything about your alphabet, but it may have something to do with the way you're setting the locale. I took off the .utf8 and it seems to work.
    – sgbj
    Jun 30, 2014 at 22:03
  • It seems the .utf8 may still be necessary - otherwise Vänt (ä) comes before Vint (i) etc, which isn't correct by the local alphabet: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, Š, Z, Ž, T, U, V, W, Õ, Ä, Ö, Ü, X, Y)
    – LeFunk
    Jun 30, 2014 at 22:14
  • Yep, checked it again - with strcoll() everything else is ordered perfectly, then the family names starting with V.. then suddenly W.. then V again. Maybe it would make more sense to create an array with the alphabet and sort the names array by it?
    – LeFunk
    Jul 1, 2014 at 0:07
  • Thanks for posting your alphabet. Unfortunately, I haven't found an easy way around it, but I did stumble across a similar question which suggests that what you're experiencing may be a possible limitation of the standard PHP library and UTF-8 encoded strings. The most upvoted answer to that question uses the Collator class from the intl extension. If I find anything else that might be of use I'll let you know.
    – sgbj
    Jul 1, 2014 at 13:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.