I want to sort an array of words alphabetically. Unfortunately, in my language (Croatian), there are double-character letters (e.g. lj, nj, dž), and letters that are not properly sorted with php sort
function (e.g. č, ć, ž, š, đ).
Here is the Croatian alphabet properly ordered (with some English letters aswell):
$alphabet = array(
'a', 'b', 'c',
'č', 'ć', 'd',
'dž', 'đ', 'e',
'f', 'g', 'h',
'i', 'j', 'k',
'l', 'lj', 'm',
'n', 'nj', 'o',
'p', 'q', 'r',
's', 'š', 't',
'u', 'v', 'w',
'x', 'y', 'z', 'ž'
);
And here is a list of words, also properly ordered:
$words = array(
'alfa', 'beta', 'car', 'čvarci', 'ćup', 'drvo', 'džem', 'đak', 'endem', 'fićo', 'grah', 'hrana', 'idealan', 'jabuka', 'koza', 'lijep', 'ljestve', 'mango',
'nebo', 'njezin', 'obrva', 'pivnica', 'qwerty', 'riba', 'sir', 'šaran', 'tikva', 'umanjenica', 'večera', 'wind', 'x-ray', 'yellow', 'zakaj', 'žena'
);
I was thinking of ways to sort it. One way was to split each word into letters. Since I didn't know how to do that because of multicharacter letters, I asked a question and got a good answer which solved that problem (see here). So I looped through the array and split each word into letters using the code provided by best answerer.
When the array was looped I had a new array (let's name it $words_splitted
). Elements of that array were arrays aswell, each representing a word.
Array
(
[0] => Array
(
[0] => a
[1] => l
[2] => f
[3] => a
)
[1] => Array
(
[0] => b
[1] => e
[2] => t
[3] => a
)
[2] => Array
(
[0] => c
[1] => a
[2] => r
)...
...[16] => Array
(
[0] => lj
[1] => e
[2] => s
[3] => t
[4] => v
[5] => e
)
The idea was to compare each letter of each array by the index value of $alphabet
variable. For example, $words_splitted[0][0]
would be compared with $words_splitted[1][0]
, and then with $words_splitted[2][0]
, etc. If we compare letters 'a' and 'b', letter 'a' has smaller index number in $alphabet
variable, so it comes before 'b'.
Unfortunately, I got stuck...and I'm not sure how to do this. Any ideas?
NOTE: PHP extensions shouldn't be used.