php array sorting with national signs and lowercase and uppercase letters

70 Views Asked by At

As I can see, this problem has not been properly solved. I think I went through all the suggested solutions, but it was based on patching a specific problem. Which clearly, in my opinion, indicates a lack of PHP support for a correct solution to the basic, nastiest situation. It's about correct sorting (ascending or descending) for an array containing lowercase and uppercase letters and specific national characters. The solution below, which I am currently using, sorts lowercase and uppercase letters correctly but throws out national characters at the very end. None of you would like it. Array_multisort, mb_strcasecmp and collate are not working properly.

(pl-PL)

f.eg.

balkon Bażant goleń Gęś Koza kuchnia mąka mięso Struś Wiewiórka Zając Łopian Świnia

        $file_info_all[] = [
        'taxon' => $taxon,
        'file_info_01c_text' => $file_info_01c_text
        ];      
    }

$file_info_01c_text <- this are my words to sorting

 usort($file_info_all, function ($a, $b) {
   return strcasecmp($a['file_info_01c_text'], $b['file_info_01c_text']);
    });

correct

balkon Bażant Gęś goleń Koza kuchnia Łopian mąka mięso Struś Świnia Wiewiórka Zając

alphabet: a ą Ą b c ć Ć d e ę Ę f g h i j k l ł Ł m n ń Ń o ó Ó p r s ś Ś t u v x y z ż Ż ź Ź

1

There are 1 best solutions below

7
Olivier On

The intl Collator does work:

$arr = explode(' ', 'balkon Bażant goleń Gęś Koza kuchnia mąka mięso Struś Wiewiórka Zając Łopian Świnia');
$collator = collator_create('pl');
usort($arr, fn($x, $y) => collator_compare($collator, $x, $y));
var_export($arr);

Output:

array (
  0 => 'balkon',
  1 => 'Bażant',
  2 => 'Gęś',
  3 => 'goleń',
  4 => 'Koza',
  5 => 'kuchnia',
  6 => 'Łopian',
  7 => 'mąka',
  8 => 'mięso',
  9 => 'Struś',
  10 => 'Świnia',
  11 => 'Wiewiórka',
  12 => 'Zając',
)

In your specific case, you can sort like this:

$file_info_all = [
    ['id' => 1, 'file_info_01c_text' => 'Bażant'],
    ['id' => 2, 'file_info_01c_text' => 'balkon']
];
$collator = collator_create('pl');
usort($file_info_all, fn($a, $b) => collator_compare($collator, $a['file_info_01c_text'], $b['file_info_01c_text']));
var_export($file_info_all);