简体   繁体   中英

How to sort non-english strings in php

How to display the following array string in alphabetically without using the collator method

$country = array('Ägypten','Afghanistan', 'Äquatorialguinea', 'Albanien');

My code is:

function compareASCII($a, $b) {
    $a1 = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
    $b1 = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
    return strcmp($a1, $b1);
}

usort($country, 'compareASCII');

Output:

Array ( [0] => Ägypten [1] => Äquatorialguinea [2] => Afghanistan [3] => Albanien )

Expected Output:

 Array ( [0] => Afghanistan [1] => Ägypten [2] => Albanien [3] => Äquatorialguinea )

How to get expected output?

Thanks for advance!!!

It can made manual (simple version, can be extended):

$country = array('Ägypten','Afghanistan', 'Äquatorialguinea', 'Albanien');

usort ($country,function($a,$b){
    $a=str_replace(array('Ä','Ö','Ü'),array('A','O','U'),$a);
    $b=str_replace(array('Ä','Ö','Ü'),array('A','O','U'),$b);
    return strcmp($a,$b);
});

print_r($country);

//Result
//Array ( [0] => Afghanistan [1] => Ägypten [2] => Albanien [3] => Äquatorialguinea )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM