Sort an array with special characters in PHP

前端 未结 5 1769
南旧
南旧 2020-12-01 17:06

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

$lang[\"ko\"] = \"coreano\"; //korean
$lang[\"ar\"] = \"árabe\"; //arabic
$lang[\"es\"] = \"esp         


        
相关标签:
5条回答
  • 2020-12-01 17:17

    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.

    0 讨论(0)
  • 2020-12-01 17:20

    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);
    
    0 讨论(0)
  • 2020-12-01 17:25

    Try this

    setlocale(LC_COLLATE, 'nl_BE.utf8');
    $array = array('coreano','árabe','español','francés');
    usort($array, 'strcoll'); 
    print_r($array);
    
    0 讨论(0)
  • 2020-12-01 17:30

    This is a non problem!

    Your initial solution works exactly as expected, Your problem is the setlocale function that is failing to set the locale and by consequence the asort($array, SORT_LOCALE_STRING) fails to sort as you expect it

    You can try your own code at phptester.net that does accept setlocale():

    $lang["ko"] = "coreano"; //korean
    $lang["ar"] = "árabe"; //arabic
    $lang["es"] = "español"; //spanish
    $lang["fr"] = "francés"; //french
    
    asort($lang,SORT_LOCALE_STRING);
    echo "<pre>";
    print_r($lang);
    echo "</pre>";
    
    echo "<pre>";
    /*this should return es_ES; 
    if returns false it has failed and asort wont return expected order
    */
    var_dump(setlocale(LC_ALL,'es_ES')); 
    echo "</pre>";
    
    asort($lang,SORT_LOCALE_STRING);
    echo "<pre>";
    print_r($lang);
    
    0 讨论(0)
  • 2020-12-01 17:34

    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 ) 
    
    0 讨论(0)
提交回复
热议问题