public static function BetterExposedFiltersHelper::sortNestedOptions in Better Exposed Filters 8.5
Same name and namespace in other branches
- 8.4 src/BetterExposedFiltersHelper.php \Drupal\better_exposed_filters\BetterExposedFiltersHelper::sortNestedOptions()
Sort nested options alphabetically.
Parameters
array $options: Array of nested unsorted options - scalar, translatable markup or taxonomy term options.
string $delimiter: The delimiter used to indicate nested level. (e.g. -Seattle)
Return value
array Alphabetically sorted array of original values.
2 calls to BetterExposedFiltersHelper::sortNestedOptions()
- BetterExposedFiltersHelperUnitTest::testSortNestedOptions in tests/
src/ Unit/ BetterExposedFiltersHelperUnitTest.php - Tests options are rewritten correctly.
- FilterWidgetBase::processSortedOptions in src/
Plugin/ better_exposed_filters/ filter/ FilterWidgetBase.php - Sorts the options for a given form element alphabetically.
File
- src/
BetterExposedFiltersHelper.php, line 169
Class
- BetterExposedFiltersHelper
- Defines a helper class for better exposed filters.
Namespace
Drupal\better_exposed_filtersCode
public static function sortNestedOptions(array $options, $delimiter = '-') {
// Flatten array of mixed values to a simple array of scalar values.
$flat_options = self::flattenOptions($options, TRUE);
$prev_key = NULL;
$level = 0;
$parent = [
$level => '',
];
// Iterate over each option.
foreach ($flat_options as $key => &$choice) {
// For each option, determine the nested level based on the delimiter.
// Example:
// - 'United States' will have level 0.
// - '-Seattle' will have level 1.
$cur_level = strlen($choice) - strlen(ltrim($choice, $delimiter));
// If we are going down a level, keep track of its parent value.
if ($cur_level > $level) {
$parent[$cur_level] = $flat_options[$prev_key];
}
// Prepend each option value with its parent for easier sorting.
// Example:
// '-Seattle' is below 'United States', its concatenated value will become
// 'United States-Seattle' etc...
$choice = $parent[$cur_level] . $choice;
// Update level and prev_key.
$level = $cur_level;
$prev_key = $key;
}
// Alphabetically sort our list of concatenated values.
asort($flat_options);
// Now use its keys to sort the original array.
return array_replace(array_flip(array_keys($flat_options)), $options);
}