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?

Tim
  • 446
  • 1
  • 5
  • 17

2 Answers2

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

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
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);
 });
Fanky
  • 1,673
  • 1
  • 18
  • 20