格式为YYYY-MM-DD的值的意外排序行为PHP Collator::asort
我在formtat格式为YYYY-MM-DD的值的意外排序行为PHP Collator::asort,php,sorting,collation,asort,Php,Sorting,Collation,Asort,我在formtatYYYY-MM-DD中发现字符串值的意外排序行为,例如使用时的2016-12-16。使用PHP的normalasort,没有问题。在Collator版本中,似乎存在一些bug,然后它似乎按照数组键进行排序 编辑:我使用PHP版本5.6.29进行此测试 我制作了一个小样本程序来说明这个问题: <?php $list["off-to-the-races"] = "2015-04-14"; $list["new-years-2015"] = "2015-01-01"; $li
YYYY-MM-DD
中发现字符串值的意外排序行为,例如使用时的2016-12-16
。使用PHP的normalasort
,没有问题。在Collator版本中,似乎存在一些bug,然后它似乎按照数组键进行排序
编辑:我使用PHP版本5.6.29进行此测试
我制作了一个小样本程序来说明这个问题:
<?php
$list["off-to-the-races"] = "2015-04-14";
$list["new-years-2015"] = "2015-01-01";
$list["ground-hog-day"] = "2015-02-02";
$list["back-to-the-future"] = "2015-08-12";
$locale = setlocale(LC_COLLATE, 0);
$col = Collator::create($locale);
$res_val = collator_get_locale( $col, \Locale::VALID_LOCALE );
$res_act = collator_get_locale( $col, \Locale::ACTUAL_LOCALE );
echo "<pre>";
printf( "Valid locale name: %s <br /> Actual locale name: %s <br />",
$res_val, $res_act );
echo "<br /><br />Raw List: <br />";
print_r($list);
$col->asort($list);
echo "<br /><br />\$col->asort(\$list): <br />";
print_r($list);
echo "<br /><br />Collator error message: <br />";
echo $col->getErrorMessage();
asort($list, $sort_flags);
echo "<br /><br />asort(\$list) (without collation): <br />";
print_r($list);
正如您所看到的,当使用$col->asort($list)
时,它不是按原始顺序排列的,但显然没有按预期进行排序
使用YYYY-MM-DD
方式将日期表示为字符串的整个要点是,如果像字符串一样排序,则在大多数实现中,它将以字母顺序和时间顺序排列
注意,如果我添加以下设置了$sort\u标志的测试用例:
$col->asort($list, 1):
Array
(
[new-years-2015] => 2015-01-01
[ground-hog-day] => 2015-02-02
[off-to-the-races] => 2015-04-14
[back-to-the-future] => 2015-08-12
)
虽然如果您知道所有值都将采用这种格式,这是一个足够的解决方法,但我希望它也可以作为一种自然排序或字符串排序—对于您的值是日期字符串和其他任意字符串的混合的情况
我不确定这是否是特定于区域设置/排序规则的。还有什么需要进一步调试的吗?您的PHP版本是什么?您是否尝试使用不同的排序标志?不同的地区呢?(我无法测试,因为我似乎忘记了在这个测试机器上更新php)。。这是类似的问题吗?PHP版本5.6.29-尚未测试不同的地区。尝试使用默认值,就像在我客户机的服务器上一样,并使用collator,因为它已嵌入到我正在使用的框架中。我尝试了不同的$sort\u falgs
只有1
给出了看起来正确的东西。
$col->asort($list, 1 );
echo "<br /><br />\$col->asort(\$list, 1): <br />";
print_r($list);
$col->asort($list, 1):
Array
(
[new-years-2015] => 2015-01-01
[ground-hog-day] => 2015-02-02
[off-to-the-races] => 2015-04-14
[back-to-the-future] => 2015-08-12
)