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

前端 未结 7 2135
眼角桃花
眼角桃花 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:36

    I think you can use strcoll:

    setlocale(LC_COLLATE, 'nl_BE.utf8');
    $array = array('Borgloon','Thuin','Lennik','Éghezée','Aubel');
    usort($array, 'strcoll'); 
    print_r($array);
    

    Result:

    Array
    (
        [0] => Aubel
        [1] => Borgloon
        [2] => Éghezée
        [3] => Lennik
        [4] => Thuin
    )
    

    You need the nl_BE.utf8 locale on your system:

    fy@Heisenberg:~$ locale -a | grep nl_BE.utf8
    nl_BE.utf8
    

    If you are using debian you can use dpkg --reconfigure locales to add locales.

    0 讨论(0)
  • 2020-11-27 20:36

    I'd be tempted to loop through the array and convert to English characters before sorting. E.g.

    <?php
      $array = array('Borgloon','Thuin','Lennik','Éghezée','Aubel');
    
      setlocale(LC_CTYPE, 'nl_BE.utf8');
    
      $newarray = array();
      foreach($array as $k => $v) {
        $newarray[$k] = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $v);
      }
    
      sort($newarray);
      print_r($newarray);
    ?>
    

    Probably not the best in terms of processing speed/resources used. But sure does make it easier to understand the code.

    Edit:

    Thinking about it now, you might be better using some kind of lookup table, something like this:

    <?php
      $accentedCharacters = array ( 'à', 'á', 'â', 'ã', 'ä', 'å', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Š', 'Ž', 'š', 'ž', 'Ÿ', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý' ); 
    
      $replacementCharacters = array ( 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'S', 'Z', 's', 'z', 'Y', 'A', 'A', 'A', 'A', 'A', 'A', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y' );
    
      $array = array('Borgloon','Thuin','Lennik','Éghezée','Aubel');
    
      $newarray = array();
      foreach($array as $k => $v) {
        $newarray[$k] = str_replace($accentedCharacters,$replacementCharacters,$v);
      }
    
      sort($newarray);
      print_r($newarray);
    ?>
    
    0 讨论(0)
  • 2020-11-27 20:42

    There are great answers here, but this is a dead simple solution for most situations.

    function globalsort($array, $in = 'UTF-8', $out = 'ASCII//TRANSLIT//IGNORE')
    {
        return usort($array, function ($a, $b) use ($in, $out) {
            $a = @iconv($in, $out, $a);
            $b = @iconv($in, $out, $b);
            return strnatcasecmp($a, $b);
        });
    }
    

    And use it like so:

    globalsort($array);
    
    0 讨论(0)
  • 2020-11-27 20:46

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

    <?php
    
    // Some 
    $strings = array('Alpha', 'Älpha', 'Bravo');
    // make it German: A, Ä, B
    setlocale(LC_COLLATE, 'de_DE.UTF8', 'de.UTF8', 'de_DE.UTF-8', 'de.UTF-8');
    usort($strings, 'strcoll');
    var_dump($strings);
    // as you can see, Ä is last, so this didn't 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

    <?php
    // data to sort
    $array = array('Borgloon','Thuin','Lennik','Éghezée','Aubel');
    // container for modified strings
    $_array = array();
    foreach ($array as $k => $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!

    0 讨论(0)
  • 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 =)

    0 讨论(0)
  • 2020-11-27 20:59

    intl comes bundled with PHP from PHP 5.3 and it only supports UTF-8.

    You can use a Collator in this case:

    $array = array('Borgloon','Thuin','Lennik','Éghezée','Aubel');
    $collator = new Collator('en_US');
    $collator->sort($array);
    print_r($array);
    

    Output:

    Array
    (
        [0] => Aubel
        [1] => Borgloon
        [2] => Éghezée
        [3] => Lennik
        [4] => Thuin
    )
    
    0 讨论(0)
提交回复
热议问题