How to use multiple sort_flags in PHP array sorting (Using SORT_LOCALE_STRING , SORT_NATURAL)?
I want to using SORT_LOCALE_STRING for UTF8 languages + SORT_NATURAL Numbers.
I want to Sort the following array:
$array=array('Alpha', 'Älpha1', 'Älpha2', 'Älpha10', 'Älpha3', 'Älpha4', 'Bravo');
My favorite result after sorting:
Array
(
[0] => Alpha
[1] => Älpha1
[2] => Älpha2
[3] => Älpha3
[4] => Älpha4
[5] => Älpha10
[6] => Bravo
)
But when using SORT_LOCALE_STRING:
<?php
$array=array('Alpha', 'Älpha1', 'Älpha2', 'Älpha10', 'Älpha3', 'Älpha4', 'Bravo');
setlocale(LC_COLLATE, 'de_DE.UTF8', 'de.UTF8', 'de_DE.UTF-8', 'de.UTF-8');
sort($array, SORT_LOCALE_STRING);
print_r($array);
?>
Results:
Array
(
[0] => Alpha
[1] => Älpha1
[2] => Älpha10
[3] => Älpha2
[4] => Älpha3
[5] => Älpha4
[6] => Bravo
)
AND when using SORT_NATURAL:
<?php
$array=array('Alpha', 'Älpha1', 'Älpha2', 'Älpha10', 'Älpha3', 'Älpha4', 'Bravo');
sort($array, SORT_NATURAL);
print_r($array);
?>
Results:
Array
(
[0] => Alpha
[1] => Bravo
[2] => Älpha1
[3] => Älpha2
[4] => Älpha3
[5] => Älpha4
[6] => Älpha10
)
How can I get result like this?!
Array
(
[0] => Alpha
[1] => Älpha1
[2] => Älpha2
[3] => Älpha3
[4] => Älpha4
[5] => Älpha10
[6] => Bravo
)
UPDATE:
I finally found the solution, By Using intl AND The Collator class.
First, enable PHP Extension intl.
Then:
<?php
$array=array('Alpha', 'Älpha1', 'Älpha2', 'Älpha10', 'Älpha3', 'Älpha4', 'Bravo');
$collator = new Collator('de_DE.UTF8');
$collator->setAttribute(Collator::NUMERIC_COLLATION, Collator::ON);
$collator->setAttribute(Collator::CASE_FIRST, Collator::LOWER_FIRST);
$collator->asort($array);
print_r($array);
?>
Results:
Array
(
[0] => Alpha
[1] => Älpha1
[2] => Älpha2
[4] => Älpha3
[5] => Älpha4
[3] => Älpha10
[6] => Bravo
)
First, enable PHP Extension intl.
Then:
<?php
$array=array('Alpha', 'Älpha1', 'Älpha2', 'Älpha10', 'Älpha3', 'Älpha4', 'Bravo');
$collator = new Collator('de_DE.UTF8');
$collator->setAttribute(Collator::NUMERIC_COLLATION, Collator::ON);
$collator->setAttribute(Collator::CASE_FIRST, Collator::LOWER_FIRST);
$collator->asort($array);
print_r($array);
?>
Results:
Array
(
[0] => Alpha
[1] => Älpha1
[2] => Älpha2
[4] => Älpha3
[5] => Älpha4
[3] => Älpha10
[6] => Bravo
)