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

前端 未结 7 2205
眼角桃花
眼角桃花 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条回答
  •  旧时难觅i
    2020-11-27 20:46

    As for strcoll I guess it was a nice idea, but doesn't seem to work:

    A while back I wrote a UTF-8 to ASCII tool that would convert "älph#bla" to "aelph-bla". You could use this to "normalize" your input to make it sortable. It's basically a replacement similar to what @Nick said.

    You should use a separate array for sorting, as calling urlify() in a usort() callback would be wasting a lot of resources. try

     $v) {
        // "normalize" utf8 to ascii
        $_array[$k] = urlify($v);
    }
    // sort the ASCII stuff (while preserving indexes)
    asort($_array);
    foreach ($_array as $key => &$v) {
        // copy the original value of the ASCIIfied element
        $v = $array[$k];
    }
    var_dump($_array);
    

    If you have PHP5.3 or the intl PECL compiled, try @Thai's solution, seems sweet!

提交回复
热议问题