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

前端 未结 7 2136
眼角桃花
眼角桃花 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 21:01

    This script should resolve in a custom way. I hope it help. Note the mb_strtolower function. You need to use it do make the function case insensitive. The reason why I didn't use the strtolower function is that it does not work well with special chars.

    <?php
    
    function customSort($a, $b) {
        static $charOrder = array('a', 'b', 'c', 'd', 'e', 'é',
                                  'f', 'g', 'h', 'i', 'j',
                                  'k', 'l', 'm', 'n', 'o',
                                  'p', 'q', 'r', 's', 't',
                                  'u', 'v', 'w', 'x', 'y', 'z');
    
        $a = mb_strtolower($a);
        $b = mb_strtolower($b);
    
        for($i=0;$i<mb_strlen($a) && $i<mb_strlen($b);$i++) {
            $chA = mb_substr($a, $i, 1);
            $chB = mb_substr($b, $i, 1);
            $valA = array_search($chA, $charOrder);
            $valB = array_search($chB, $charOrder);
            if($valA == $valB) continue;
            if($valA > $valB) return 1;
            return -1;
        }
    
        if(mb_strlen($a) == mb_strlen($b)) return 0;
        if(mb_strlen($a) > mb_strlen($b))  return -1;
        return 1;
    
    }
    $array = array('Borgloon','Thuin','Lennik','Éghezée','Aubel');
    usort($array, 'customSort');
    

    EDIT: Sorry. I made many mistakes in the last code. Now is tested.

    EDIT {2}: Everything with multibyte functions.

    0 讨论(0)
提交回复
热议问题