How can I sort an array of UTF-8 strings in PHP?

前端 未结 7 2174
眼角桃花
眼角桃花 2020-11-27 20:24

need help with sorting words by utf-8. For example, we have 5 cities from Belgium.

$array = array(\'Borgloon\',\'Thuin\',\'Lennik\',\'Éghezée\',\'Aubel\');
s         


        
7条回答
  •  余生分开走
    2020-11-27 20:58

    If you want to use native solution, so i can propose this one

    function compare($a, $b)
    {
            $alphabet = 'aąbcćdeęfghijklłmnnoóqprstuvwxyzźż'; // i used polish letters
            $a = mb_strtolower($a);
            $b = mb_strtolower($b);
    
            for ($i = 0; $i < mb_strlen($a); $i++) {
                if (mb_substr($a, $i, 1) == mb_substr($b, $i, 1)) {
                    continue;
                }
                if ($i > mb_strlen($b)) {
                    return 1;
                }
                if (mb_strpos($alphabet, mb_substr($a, $i, 1)) > mb_strpos($alphabet, mb_substr($b, $i, 1))) {
                    return 1;
                } else {
                    return -1;
                }
            }
    }
    
    usort($needed_array, 'compare');
    

    Not sure, that is the best solution, but it works for me =)

提交回复
热议问题