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');
有帮助吗?

解决方案 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');

其他提示

Try using Collator::asort from the intl module:

<?php
$collator = collator_create('es_ES');
$collator->asort($array);

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:

  1. Sort using uasort and create your own comparison function.
  2. Generate a mapping from the ascii version of your strings, to the real one, and sort on the keys.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top