Sort an Array with Special Characters in PHP

Sort an array with special characters in PHP

Try sorting by translitterated names:

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

uasort($lang, 'compareASCII');

print_r($lang);

PHP sort array with special characters

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

How to sort values with special chars in array?

Solution linked by @Sbls in comments

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

How to sort array with special characters or numbers in PHP?

If by "special chars" you mean chars specific to a particular language I suggest using Collator from the intl package of extensions.

For example for Polish standard sort of:

$array = [ 'a', 'ą', 'b', 'z' ];

will give you:

array(4) {
[0] =>
string(1) "a"
[1] =>
string(1) "b"
[2] =>
string(1) "z"
[3] =>
string(2) "ą"
}

while sorting using Collator the correct one:

$collator = new Collator('pl_PL');
$collator->sort($array);

gives the correct:

array(4) {
[0] =>
string(1) "a"
[1] =>
string(2) "ą"
[2] =>
string(1) "b"
[3] =>
string(1) "z"
}

If you cannot use the pecl intl but using PHP >=7.0.0 you can use this lib:
https://github.com/voku/portable-utf8

for example:

$array = [ 'a', 'ą', 'b', 'z' ];

function mysort($a, $b) {
return UTF8::strcmp($a, $b);
}

use voku\helper\UTF8;
usort($array, 'mysort');

It does not require mbstring or intl to be installed (although suggests it).

You should not rely on setlocale as it is based on the locales installed in the particular system and those may not only be not installed, but also their names may differ (between Windows and *nix, but also between *nixes).

sort array with special characters in php

I ended up installing the French language pack to my server and using the following :

setlocale(LC_COLLATE, 'fr_CA.utf8');
asort($array, SORT_LOCALE_STRING);

Works for my needs...

Sorting an array based on special character set in php

Since PHP can do everything except collections.Counter identically with a different function name or syntax. First you would need to use count_chars($word, 1) as a substitute for collections.Counter, followed by mapping the returned array to the character using chr.

Afterwards its just replacing the Python syntax with the PHP equivalent.

Example: https://3v4l.org/V6HBg

function groupStrings($input)
{
$words = $dict = [];
foreach ($input as $word) {
//emulate python collections.Counter() using count_chars()
$wordDict = \count_chars($word, 1);

//get the character value returned from keys of count_chars()
$key = \array_map(function($v) {
return \chr($v);
}, \array_keys($wordDict));

//sort alphabetically A-Z (ignores case)
\natcasesort($key);

//create an associative index from the key
$key = \implode('', $key);

if (!\array_key_exists($key, $dict)) {
$dict[$key] = [];
}
$dict[$key][] = $word;
}

foreach ($dict as $key => $word) {
$words[] = \implode(',', $word);
}

return \implode(',', $words);
}

$input = ['student', 'students', 'dog', 'studentssess', 'god', 'cat'];
echo groupStrings($input);

Result:

student,students,studentssess,dog,god,cat

Full Result:

may,amy,yam,student,students,studentssess,dog,god,cat,act,tab,bat,flow,wolf,lambs,balms,looped,poodle

Simplified version https://3v4l.org/SuAI5

Since you're only interested in the characters in each word and not the frequency of them, we can replace the costly count_chars and array_map conversion of the keys to characters, and use array_unique on str_split instead.

function groupStrings($input)
{
$dict = \array_reduce($input, function(array $out, $in) {
//retrieve the unique characters of each word
$key = \array_unique(\str_split($in));

//sort alphabetically A-Z (ignores case)
\natcasesort($key);

//create an associative index from the key
$key = \implode('', $key);

if(!\array_key_exists($key, $out)) {
$out[$key] = [];
}
$out[$key][] = $in;

return $out;
}, []);

return \implode(',', \array_map(function($word) {
return \implode(',', $word);
}, $dict));
}

$input = ['student', 'students', 'dog', 'studentssess', 'god', 'cat'];
echo groupStrings($input);

Sorting array ignoring special characters in PHP

How about this:

$foo = array('9:00', '22:00', '12:00', '*15:00');

usort($foo, function($a, $b) {
$a = preg_replace('|[^\d:]|', '', $a);
$b = preg_replace('|[^\d:]|', '', $b);

return strnatcmp($a, $b);
});

print_r($foo);

Output:

Array
(
[0] => 9:00
[1] => 12:00
[2] => *15:00
[3] => 22:00
)


Related Topics



Leave a reply



Submit