Sortieren Sie ein Array mit Sonderzeichen in PHP
Frage
Ich habe ein Array, das die Namen der Sprachen auf Spanisch enthält: generasacodicetagpre.
Ich muss das Array bestellen und den Index-Association aufrechterhalten, also verwende ich assoort () mit dem
Die erwartete Ausgabe wäre in dieser Reihenfolge:
- .
- Array ([AR]=> árabe [kO]=> coreano [es]=> español [fr]=> francés)
das ist jedoch, was ich empfange:
- .
- Array ([kO]=> coreano [es]=> español [fr]=> francés [ar]=> Árabe)
Ich vermisse etwas?Vielen Dank für Ihr Feedback!(Mein Server verwendet PHP-Version 5.2.13)
- Array ([kO]=> coreano [es]=> español [fr]=> francés [ar]=> Árabe)
Lösung
Try sorting by translitterated names:
function compareASCII($a, $b) {
$at = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
$bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
return strcmp($at, $bt);
}
uasort($lang, 'compareASCII');
print_r($lang);
Andere Tipps
You defined your locale incorrectly in setlocale()
.
Change:
setlocale(LC_ALL,'es_ES.UTF-8');
To:
setlocale(LC_ALL,'es_ES');
Output:
Array ( [ar] => árabe [ko] => coreano [es] => español [fr] => francés )
The documentation for setlocale
mentions that
Different systems have different naming schemes for locales.
It's possible that your system does not recognize the locale as es_ES
. If you are on Windows, try esp_ESP
instead.
Try this
setlocale(LC_COLLATE, 'nl_BE.utf8');
$array = array('coreano','árabe','español','francés');
usort($array, 'strcoll');
print_r($array);