How to sort an array of UTF-8 strings?

后端 未结 8 790
刺人心
刺人心 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:52

    $a = array( 'Кръстев', 'Делян1', 'делян1', 'Делян2', 'делян3', 'кръстев' );
    $col = new \Collator('bg_BG');
    $col->asort( $a );
    var_dump( $a );
    

    Prints:

    array
      2 => string 'делян1' (length=11)
      1 => string 'Делян1' (length=11)
      3 => string 'Делян2' (length=11)
      4 => string 'делян3' (length=11)
      5 => string 'кръстев' (length=14)
      0 => string 'Кръстев' (length=14)
    

    The Collator class is defined in PECL intl extension. It is distributed with PHP 5.3 sources but might be disabled for some builds. E.g. in Debian it is in package php5-intl .

    Collator::compare is useful for usort.

提交回复
热议问题