wc_asort_by_locale()WC 4.6.0

Sort array according to current locale rules and maintaining index association. By default tries to use Collator from PHP Internationalization Functions if available. If PHP Collator class doesn't exists it fallback to removing accepts from a array and by sorting with uasort( $data, 'strcmp' ) giving support for ASCII values.

No Hooks.

Return

Array.

Usage

wc_asort_by_locale( $data, $locale );
$data(array) (required) (passed by reference — &)
List of values to sort.
$locale(string)
Locale.
Default: ''

Changelog

Since 4.6.0 Introduced.

wc_asort_by_locale() code WC 8.7.0

function wc_asort_by_locale( &$data, $locale = '' ) {
	// Use Collator if PHP Internationalization Functions (php-intl) is available.
	if ( class_exists( 'Collator' ) ) {
		try {
			$locale   = $locale ? $locale : get_locale();
			$collator = new Collator( $locale );
			$collator->asort( $data, Collator::SORT_STRING );
			return $data;
		} catch ( IntlException $e ) {
			/*
			 * Just skip if some error got caused.
			 * It may be caused in installations that doesn't include ICU TZData.
			 */
			if ( Constants::is_true( 'WP_DEBUG' ) ) {
				error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
					sprintf(
						'An unexpected error occurred while trying to use PHP Intl Collator class, it may be caused by an incorrect installation of PHP Intl and ICU, and could be fixed by reinstallaing PHP Intl, see more details about PHP Intl installation: %1$s. Error message: %2$s',
						'https://www.php.net/manual/en/intl.installation.php',
						$e->getMessage()
					)
				);
			}
		}
	}

	$raw_data = $data;

	array_walk(
		$data,
		function ( &$value ) {
			$value = remove_accents( html_entity_decode( $value ) );
		}
	);

	uasort( $data, 'strcmp' );

	foreach ( $data as $key => $val ) {
		$data[ $key ] = $raw_data[ $key ];
	}

	return $data;
}