Home > Blockchain >  How to use natsort in different language?
How to use natsort in different language?

Time:02-11

I'm trying to sort an array using natsort/natcasesort. But I'm having trouble with non-English (In Turkish) characters. This is the only option that works for me at the moment. How can I overcome this problem? For example, the array looks like this:

   $texts= array("A","Ü","Ç","Ş","Ğ");
    natcasesort($texts);
    echo '<pre>'; print_r($files); echo '</pre>';

Output:

Array
(
    [0] => A
    [2] => Ç
    [1] => Ü
    [4] => Ğ
    [3] => Ş
)


$all_characters = [ "ğ", "Ğ", "ç", "Ç", "ş", "Ş", "ü", "Ü", "ö", "Ö", "ı", "İ" ];
    
$alphabet_all = "AaBbCcÇçDdEeFfGgĞğHhIıİiJjKkLlMmNnOoÖöPpQqRrSsŞşTtUuÜüVvWwXxYyZz";
$small_letters = array("İ","I","Ş","Ğ","Ö","Ü","Ç");
$capital_letters = array("i","ı","ş","ğ","ö","ü","ç");

How should it be ?
A, Ç, Ğ, Ş, Ü

CodePudding user response:

Natsort is not suitable for language-specific sorting. That's what the Collator class is for.

$all_characters = [ "ğ", "Ğ", "ç", "Ç", "ş", "Ş", "ü", "Ü", "ö", "Ö", "ı", "İ" ];

$collator = new Collator('tr_TR');
$collator->sort($all_characters);

echo implode(', ',$all_characters);
//ç, Ç, ğ, Ğ, ı, İ, ö, Ö, ş, Ş, ü, Ü

CodePudding user response:

You can do this by comparing ASCII Characters. Try Something like this.

$texts= array("A","Ü","Ç","Ş","Ğ");
function compareASCII($a, $b) {
    $at = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
    $bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
    return strcmp($at, $bt);
}

uasort($texts, 'compareASCII');
echo '<pre>'; print_r($texts); echo '</pre>';

Your Output will be like

Array
(
    [0] => A
    [2] => Ç
    [4] => Ğ
    [3] => Ş
    [1] => Ü
)
  • Related