3

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" }

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I have been added setlocale to my php script... but it seems that sort doesnot work=(
all data is getting from db, but I can't modify it collations, or something else in it=(
@vladimir - Are you sure you're using a sortable array? sort requires a 1-dimensional array... php.net/manual/en/function.sort.php - if you have more dimensions, you have to use usort
please see my updated question, for clear, how looks my array
0

You should change collocation to utf8_unicode_ci which sorts Latvian accent symbols correctly. If You can not modify database it can be done on-the-fly:

SET NAMES 'utf8_latvian_ci';

SELECT keyword
FROM ctest
ORDER BY CONVERT(keyword USING ucs2) COLLATE ucs2_latvian_ci,
CONVERT(keyword USING ucs2) COLLATE ucs2_bin ASC;

Source: http://laacz.lv/2010/10/28/ka-ieks-mysql-sakartot-latviesu-burtus-pareiza-seciba/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.