Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sort array with special characters

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?

like image 446
Tim Avatar asked Apr 19 '18 07:04

Tim


2 Answers

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

like image 59
Anant Kumar Singh Avatar answered Oct 30 '22 10:10

Anant Kumar Singh


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);
 });
like image 34
Fanky Avatar answered Oct 30 '22 10:10

Fanky