Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

setlocale - Sort an array with special characters in PHP

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...