【问题标题】:Sort an array of dates using usort() and sort() functions [duplicate]使用 usort() 和 sort() 函数对日期数组进行排序[重复]
【发布时间】:2012-11-18 19:53:07
【问题描述】:

可能重复:
Sort an array of dates using usort() and sort() functions by the timestamp converted by mktime()

我正在尝试仅使用 sort() 和 usort() 对日期数组进行排序 - 不使用 mktime()。我正在尝试比较月、日和年,但无法得到正确的结果,而且它给了我一堆警告。 将不胜感激。

$dates = array ('10-10-2003', '2-17-2002', '2-16-2003','1-01-2005', '10-10-2004' );
function toTime($date) {

return sort ($date, SORT_STRING);
}

function sortByTime($a, $b) {
$a = toTime($a);
$b = toTime($b);
if($a == $b) {
    return 0;
}
return $a < $b ? -1 : 1 ;
}

usort($dates, 'sortByTime');
print_r($dates);

非常感谢。

【问题讨论】:

  • 你在 toTime 函数中做了什么?
  • Aerik,在 toTime 函数中,我试图对数组字符串进行排序。我尝试将mm、dd、yyyy分开,但没有成功。
  • vascowite,是的 - 这也是我的问题。但是这里我不能使用 mktime() 转换器。
  • 您收到什么警告?您可以在问题中包含您的 toTime 函数吗?
  • @Emil Vikstrom: function toTime($date) { $list = list($month, $day, $year) = explode('-', $date);返回排序($列表);我收到 sort() 的警告 - 它要求数组,explode() 函数 - 第二个参数应该是字符串。我知道这个功能是不正确的,也许真的很愚蠢。我刚开始学习 PHP,所以弄脏了我的手。将不胜感激。

标签: php date sorting


【解决方案1】:

使用uksort 通过回调按键排序

在回调中简单地将日期解析为时间戳并使用简单的比较

须藤代码:

function cmp($a, $b)
{
    global $array;
    return strcmp($array[$a]['db'], $array[$b]['db']);
}

uksort($array, 'cmp');

【讨论】:

  • 不能使用 uksort() :( 只有 usort() 和 sort()
  • 这是正规教育理念 :) 打破你的头脑,但不要使用方便的方法 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 2018-02-01
  • 2021-07-26
相关资源
最近更新 更多