How to sort values with special chars in array?

一曲冷凌霜 提交于 2019-12-11 09:15:05

问题


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:

  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.



回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!