Сортировать массив со специальными символами в PHP

StackOverflow https://stackoverflow.com//questions/10649473

  •  11-12-2019
  •  | 
  •  

Вопрос

У меня есть массив, который удерживает названия языков по-испански:

$lang["ko"] = "coreano"; //korean
$lang["ar"] = "árabe"; //arabic
$lang["es"] = "español"; //spanish
$lang["fr"] = "francés"; //french
.

Мне нужно заказать массив и поддерживать индексную ассоциацию, поэтому я использую asort () с <Сильный> Сортировка_locale_String

setlocale(LC_ALL,'es_ES.UTF-8'); //this is at the beginning (config file)
asort($lang,SORT_LOCALE_STRING);
print_r($lang);
.

Ожидаемый вывод будет в этом порядке:

    .
  • массив ([ar]=> árabe [ko]=> coreano [es]=> español [fr]=> francés)

    Тем не менее, это то, что я получаю:

      .
    • массив ([ko]=> coreano [es]=> español [fr]=> francés [ar]=> árabe)

      Я что-то упускаю?Спасибо за ваш отзыв!(мой сервер использует PHP версии 5.2.13)

Это было полезно?

Решение

Try sorting by translitterated names:

function compareASCII($a, $b) {
    $at = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
    $bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
    return strcmp($at, $bt);
}

uasort($lang, 'compareASCII');

print_r($lang);

Другие советы

You defined your locale incorrectly in setlocale().

Change:

setlocale(LC_ALL,'es_ES.UTF-8');

To:

setlocale(LC_ALL,'es_ES');

Output:

Array ( [ar] => árabe [ko] => coreano [es] => español [fr] => francés ) 

The documentation for setlocale mentions that

Different systems have different naming schemes for locales.

It's possible that your system does not recognize the locale as es_ES. If you are on Windows, try esp_ESP instead.

Try this

setlocale(LC_COLLATE, 'nl_BE.utf8');
$array = array('coreano','árabe','español','francés');
usort($array, 'strcoll'); 
print_r($array);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top