OSX / FreeBSD上的PHP setlocale不起作用

时间:2014-01-17 09:34:10

标签: php macos sorting locale freebsd

我在FreeBSD / OSX上遇到问题,并通过locale对结果进行排序。这是代码(在linux上运行正常)

<?php
header('Content-Type: text/html; charset=utf-8');
echo "<pre>"; 
setlocale(LC_ALL, 'cs_CZ.UTF-8', 'Czech');
echo "Set locale: ". setlocale(LC_ALL, 0) . "\n";
$countries = array(
    'Bulharsko',
    'Česko',
    'Polsko',
    'Čína'
);

sort($countries, SORT_LOCALE_STRING);
print_r($countries);
?>

我在OSX上检查了我得到的语言环境:

$locale -a
...
cs_CZ
cs_CZ.ISO8859-2
cs_CZ.UTF-8
...

然后按文件:

$ pwd
/usr/share/locale/cs_CZ.UTF-8
$ ls -la
total 24
drwxr-xr-x    8 root  wheel   272 Oct 23 18:07 ./
drwxr-xr-x  226 root  wheel  7684 Oct 23 18:07 ../
lrwxr-xr-x    1 root  wheel    28 Oct 23 18:06 LC_COLLATE@ -> ../la_LN.US-ASCII/LC_COLLATE
lrwxr-xr-x    1 root  wheel    17 Oct 23 18:06 LC_CTYPE@ -> ../UTF-8/LC_CTYPE
drwxr-xr-x    3 root  wheel   102 Oct 23 18:07 LC_MESSAGES/
-r--r--r--    1 root  wheel    36 Oct 23 18:06 LC_MONETARY
lrwxr-xr-x    1 root  wheel    29 Oct 23 18:06 LC_NUMERIC@ -> ../cs_CZ.ISO8859-2/LC_NUMERIC
-r--r--r--    1 root  wheel   397 Oct 23 18:06 LC_TIME

有趣的是,OSX中的LC_COLLATE每个语言都指向同一个文件。系统信息:

PHP 5.4.23 (cli) (built: Dec 16 2013 00:36:15) 
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

(OSX 10.9.1): Darwin MBP.local 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE_X86_64 x86_64

知道如何使用区域设置进行排序吗?

1 个答案:

答案 0 :(得分:0)

改为使用Collat​​or(Linux / Win / Mac兼容):

$usedLocale = setlocale (LC_COLLATE, 'cs_CZ.utf8', 'cs_CZ.UTF-8', 'Czech', 'cs_CZ', 'cs');
$collator = new Collator($usedLocale);
$collator->asort($countries, SORT_LOCALE_STRING);