问题
First, I set the proper locale to spanish:
setlocale(LC_ALL, 'es_ES');
This array holds a list of languages which must be reordered alphabetically.
$lang['ar'] = 'árabe';
$lang['fr'] = 'francés';
$lang['de'] = 'alemán';
So I do this:
asort($lang,SORT_LOCALE_STRING);
The final result is:
- alemán
- francés
- árabe
...and it should be:
- árabe
- alemán
- francés
The asort() function is sending the á character to the bottom of the ordered list. How can I avoid this issue? Thanks!
Solution linked by @Sbls
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');
回答1:
It is likely that the comparison checks the multibyte value of the character, and á
in that case is probably greater than z
, so it will show afterwards. If you want a comparison that does not take that into account, I see two possibilites:
- Sort using uasort and create your own comparison function.
- Generate a mapping from the ascii version of your strings, to the real one, and sort on the keys.
回答2:
Try using Collator::asort from the intl
module:
<?php
$collator = collator_create('es_ES');
$collator->asort($array);
回答3:
Solution linked by @Sbls in comments
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');
来源:https://stackoverflow.com/questions/20924776/how-to-sort-values-with-special-chars-in-array