5

I know this was asked many times, but still I can't find bullet proof solution.

Here is my array which needs to be sorted alphabetically.

setlocale(LC_ALL, 'sl_SI.utf8');

$a = [
   'č' => [...],  
   'a' => [...],
   'š' => [...], 
   'u' => [...] 
]

How can I sort it by keys?

2
  • It gives output this, What your desire output ? Commented Apr 19, 2018 at 7:38
  • I want it sorted by keys [a => [], č => [], š => [], u => []] Commented Apr 19, 2018 at 7:38

2 Answers 2

5

Taken reference from this example:-Sort an array with special characters in PHP

Explanation:-

  1. Get array keys using array_keys() method

  2. Sort keys based on iconv() AND strcmp() functions

  3. Iterated over the sorted key array and get their corresponding value from initial array.Save this key value pair to your resultant array

Do like below:-

<?php

setlocale(LC_ALL, 'sl_SI.utf8');

$a = [
   'č' => [12],  
   'a' => [23],
   'š' => [45], 
   'u' => [56] 
];


$index_array = array_keys($a);

function compareASCII($a, $b) {
    $at = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
    $bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
    return strcmp($at, $bt);
}

uasort($index_array, 'compareASCII');

$final_array = [];
foreach($index_array as $index_arr){

$final_array[$index_arr] = $a[$index_arr];
}

print_r($final_array);

Output:- https://eval.in/990872

Reference:-

iconv()

strcmp()

uasort

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

4 Comments

What about sort($index_array, SORT_LOCALE_STRING);? Why is a comparison using iconv() and strcmp() better? :-)
This works! Also now I tried with ksort($array, SORT_LOCALE_STRING), which works too, but only on linux environment.
@PhilippMaurer sort($index_array, SORT_LOCALE_STRING);? not worked:-eval.in/990875
@Tim glad to help you :):)
4

Use strcoll().

setlocale(LC_ALL, 'sl_SI.utf8');
// setlocale(LC_ALL,"cs_CZ.UTF-8"); //for Czech characters etc.
uksort($a, 'strcoll');

You can use usort for sorting multidimensional arrays by value this way:

 setlocale(LC_ALL, 'sl_SI.utf8');
 // setlocale(LC_ALL,"cs_CZ.UTF-8"); //for Czech characters etc.
 usort($posts, function($a, $b) {
    return strcoll($a["post_title"], $b["post_title"]);
 });

or for objects:

 setlocale(LC_ALL, 'sl_SI.utf8');
 // setlocale(LC_ALL,"cs_CZ.UTF-8"); //for Czech characters etc.
 usort($posts, function($a, $b) {
    return strcoll($a->post_title, $b->post_title);
 });

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.