Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Latvian array of words sorting

I have a question.. I have an array of Latvian words (i.e Agita Matīsa, Āris Matisovičs, Baiba Matisone), and I need to sort this array in alphabetical order... So I dont know how to do it, because it's not a usual latin alphabet... can onyone help me? here is some code, which describe how I get this array:

foreach($pacienti as $key => $val)
                        {
                            $person = array();
                            foreach($val as $p)
                            {
                                $person[] = $p; 
                            }
                            $person = array_unique($person);


                            foreach($person as $pac)
                            {
                                if ($key != null)
                                    $div_patienti .= "<div id='".$key."' class='filial_r15'>".$pac."</div>";    
                            }

                        }

UPD1

here is array value:

array(1) { [0]=> string(36) "agita&nbsp;matīsa&nbsp;080569-11863" } array(1) { [0]=> string(35) "aija&nbsp;matīsa&nbsp;240938-11562" }
like image 221
vladimir Avatar asked Mar 25 '26 14:03

vladimir


1 Answers

Set your locale to Latvian, and then sort your array using the SORT_LOCALE_STRING flag.

setlocale(LC_ALL, 'lv_LV');
sort($array, SORT_LOCALE_STRING);

Alternatively, you could use usort with strcoll as a locale-sensitive string comparison if you want to do some sort of custom sorting based on a complex key structure.

setlocale(LC_ALL, 'lv_LV');
usort($array, function($a, $b) {
    return strcoll($a['key'], $b['key']);
});

PS - if this is coming out of a database, probably best to set your DB to handle the (Latin-2?) character set / collation so that you can pull your data out in the correct order.

like image 97
Steven Moseley Avatar answered Mar 27 '26 04:03

Steven Moseley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!