Problem: Need to sort an array that contains strings, for example the original name of the languages, based on specific language e.g. Greek (el), in such way that the names written in Greek will be sorted first and then the rest of the names in other languages.
Input:
$arLanguages = [
'English',
'Αγγλικά',
'Русский',
'Ρωσική',
'Ελληνικά',
];
Expected Output:
Array
(
[0] => Αγγλικά
[1] => Ελληνικά
[2] => Ρωσική
[3] => English
[4] => Русский
)
What I tried:
setlocale(LC_COLLATE, 'el');
asort($arLanguages);
print_r($arLanguages);
Result: Nothing happens.
EDIT: My PHP version is 7.3.
EDIT 1: A solution by Simone doesn't work for Chinese and Japanese languages. I think is something to do with multi-byte characters or because Chinese and Japanese use latin alphabet too.
Dear SO community, how the described problem could be solved in the best possible way?
Thanks for your time!
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning // This code is contributed by hrithikgarg03188. Bubble Sort Approach: The basic approach to sort the given strings in lexicographic order is by using bubble sort.
Given a string str and an array of strings strArr [], the task is to sort the array according to the alphabetical order defined by str . Note: str and every string in strArr [] consists of only lower case alphabets. Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Sorting algorithms are a set of instructions that take an array or list as an input and arrange the items into a particular order. Sorts are most commonly in numerical or a form of alphabetical (called lexicographical) order, and can be in ascending (A-Z, 0-9) or descending (Z-A, 9-0) order.
1 Using the Arrays.sort () Method. In Java, Arrays is the class defined in the java.util package that provides sort () method to sort an array in ascending order. 2 Sort String Array in Ascending Order or Alphabetical Order. ... 3 Sort String Array in Descending Order or Reverse Natural Order 4 Using the reverseOrder () Method. ...
You can use Collator::sort
$arLanguages = [
'English',
'Αγγλικά',
'Русский',
'Ρωσική',
'Ελληνικά',
];
$coll = collator_create( 'el' );
collator_asort( $coll, $arLanguages ); // to preserve indexes
print_r($arLanguages); //output Array ( [0] => Αγγλικά [1] => Ελληνικά [2] => Ρωσική [3] => English [4] => Русский )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With