Order values in German alphabetical order with PHP
Order numerical values or things like dates is no problem with PHP. Even ordering by alphabet isn't that big of a deal. But when you use another language then English, things get interesting.
Sorting by a date would look something like this:
$collection = new ArrayCollection($externalPartners);
/** @var \ArrayIterator $iterator */
$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
/* @var LifecycleInterface $a */
/* @var LifecycleInterface $b */
return ($a->getCreated() >= $b->getCreated()) ? 1 : -1;
});
$sorted = iterator_to_array($iterator);
Just putting in a string
instead of getCreated()
would sort them in alphabetical order. But only in the English language. German for example contains special characters like Ä
, Ü
and Ö
, which would be added to the end of the alphabet which isn't correct in the German language.
To sort in a specific language you can use the \Collator
class. Sorting with this would look like the following:
$collection = new ArrayCollection($references);
/** @var \ArrayIterator $iterator */
$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
/* @var NameInterface $a */
/* @var NameInterface $b */
$collator = new \Collator('de_DE');
return $collator->compare($a->getName(), $b->getName());
});
$sorted = iterator_to_array($iterator);