How to sort an array of UTF-8 strings?

后端 未结 8 774
刺人心
刺人心 2020-11-27 04:32

I currentyl have no clue on how to sort an array which contains UTF-8 encoded strings in PHP. The array comes from a LDAP server so sorting via a database (would be no probl

8条回答
  •  温柔的废话
    2020-11-27 04:58

    I found this following helper function to convert all letters of a string to ASCII letters very helpful here.

    function _all_letters_to_ASCII($string) {
      return strtr(utf8_decode($string), 
        utf8_decode('ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'),
        'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy');
    }
    

    After that a simple array_multisort() gives you what you want.

    $array = array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich');
    $reference_array = $array;
    
    foreach ($reference_array as $key => &$value) {
      $value = _all_letters_to_ASCII($value);
    }
    var_dump($reference_array);
    
    array_multisort($reference_array, $array);
    var_dump($array);
    

    Of course you can make the helper function fit more advanced needs. But for now, it looks pretty good.

    array(6) {
      [0]=> string(6) "Birnen"
      [1]=> string(5) "Apfel"
      [2]=> string(8) "Ungetume"
      [3]=> string(5) "Apfel"
      [4]=> string(9) "Ungetiere"
      [5]=> string(10) "Osterreich"
    }
    
    array(6) {
      [0]=> string(5) "Apfel"
      [1]=> string(6) "Äpfel"
      [2]=> string(6) "Birnen"
      [3]=> string(11) "Österreich"
      [4]=> string(9) "Ungetiere"
      [5]=> string(9) "Ungetüme"
    }
    

提交回复
热议问题