Sort an array with special characters in PHP

2019-01-18 23:53发布

I have an array that holds the names of languages in spanish:

$lang["ko"] = "coreano"; //korean
$lang["ar"] = "árabe"; //arabic
$lang["es"] = "español"; //spanish
$lang["fr"] = "francés"; //french

I need to order the array and maintain index association, so I use asort() with the SORT_LOCALE_STRING

setlocale(LC_ALL,'es_ES.UTF-8'); //this is at the beginning (config file)
asort($lang,SORT_LOCALE_STRING);
print_r($lang);

The expected output would be in this order:

  • Array ( [ar] => árabe [ko] => coreano [es] => español [fr] => francés )

However, this is what I'm receiving:

  • Array ( [ko] => coreano [es] => español [fr] => francés [ar] => árabe )

Am I missing something? Thanks for your feedback! (my server is using PHP Version 5.2.13)

4条回答
戒情不戒烟
2楼-- · 2019-01-19 00:28

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.

查看更多
老娘就宠你
3楼-- · 2019-01-19 00:38

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);
查看更多
淡お忘
4楼-- · 2019-01-19 00:47

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 ) 
查看更多
【Aperson】
5楼-- · 2019-01-19 00:48

Try this

setlocale(LC_COLLATE, 'nl_BE.utf8');
$array = array('coreano','árabe','español','francés');
usort($array, 'strcoll'); 
print_r($array);
查看更多
登录 后发表回答