Skip to content

Instantly share code, notes, and snippets.

@reanim8ed
Last active July 23, 2021 13:35
Show Gist options
  • Save reanim8ed/425bbcee94c7b86a219f1f0714d926c7 to your computer and use it in GitHub Desktop.
Save reanim8ed/425bbcee94c7b86a219f1f0714d926c7 to your computer and use it in GitHub Desktop.
[Order ArrayCollection by array & lt chars] #symfony #php
// $optionNames - array to sort by;
// $options - array collection to sort

$collator = new Collator('lt_LT');
$collator->sort($optionNames);

// Reorder iterator by already ordered option names
$optionIterator = $options->getIterator();

$optionIterator->uasort(
    function ($first, $second) use ($optionNames) {
        foreach ($optionNames as $optionName) {
            if ($first->getName() === $optionName) {
                return -1;
            }
            if ($second->getName() === $optionName) {
                return 1;
            }
        }

        return 0;
    }
);

// Make clean collection out of reordered iterator
$orderedOptions = iterator_to_array($optionIterator, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment