views:

21

answers:

1

I´m using strcmp in combination with usort in order to sort an array of country names. Currently, the sort order is:

Belgien
Frankreich
Italien
Luxemburg
Niederlande
Spanien
United Kingdom
Österreich

Which is correct, apart from the position of Österreich. It should be between Niederlande and Spanien.

I also tried strnatcmp and strcoll (with setlocale), but the sort order was not the way I wanted it. The results are not from a mysql db, so sorting via a mysql query is not an option.

A: 

This works (assumes script is in UTF-8):

<?php

$arr = array(
"Belgien",
"Frankreich",
"Italien",
"Luxemburg",
"Niederlande",
"United Kingdom",
"Österreich",
"Spanien",
"Ásdf",
);

setlocale(LC_COLLATE, "pt_PT.UTF8");
usort($arr, 'strcoll');
print_r($arr);

gives me:

Array
(
    [0] => Ásdf
    [1] => Belgien
    [2] => Frankreich
    [3] => Italien
    [4] => Luxemburg
    [5] => Niederlande
    [6] => Österreich
    [7] => Spanien
    [8] => United Kingdom
)

However, this is painful; it requires the locale to be installed. locale -a gives you the installed locales, e.g. in my machine it gives me:

C
en_US
en_US.iso88591
en_US.utf8
POSIX
pt_PT.utf8
Artefacto
I tried your code and setlocale(LC_COLLATE, "de_DE.UTF8");, but it wont sort me the array in the correct order, although I verified that the locale is available.
Max
@Max Perhaps your script is not in UTF-8. Try de_DE.iso88591
Artefacto