0

我有一个看起来像这样的 PHP 数组:

$dates = array();
$dates['01-07-2013'] = 'dummy data';
$dates['01-21-2013'] = 'dummy data';
$dates['01-28-2013'] = 'dummy data';
$dates['01-20-2012'] = 'dummy data';

使用ksort($dates)时,它们没有正确排序。有没有办法像这样对键进行排序?

我希望排序返回:

'01-30-2012',
'01-07-2013',
'01-21-2013',
'01-28-2013',
4

4 回答 4

9

Those aren't dates, as far as PHP is concerned. They're strings, so it's applying standard string sorting rules to it.

You'll need to define a custom sort function for use with usort(), or convert those dates to a format that IS sortable as a string, e.g.

yyyy-mm-dd
于 2013-05-09T15:12:49.480 回答
0
$dates = array();
$dates[time()] = 'dummy data';

Converting to unix timestamp may help as it is just a number (integer) that can be sorted easily.

于 2013-05-09T15:13:16.623 回答
0

ksort默认排序类型为SORT_REGULAR

SORT_REGULAR - 正常比较项目(不要更改类型)

并且您的日期格式将在 PHP 中评估为通用字符串。

您需要对这些进行格式化,以便将它们作为字符串排序。

于 2013-05-09T15:18:41.880 回答
0

您可以使用 uksort,但在比较功能中如下所示:

function sort_func($date1, $date2){
    return strtotime(str_replace("-","/", $date1)) - strtotime(str_replace("-","/", $date2));
}

uksort($dates, "sort_func");
于 2013-05-09T15:42:38.413 回答