为了账号安全,请及时绑定邮箱和手机立即绑定

usort 将字符串转换为日期

usort 将字符串转换为日期

PHP
斯蒂芬大帝 2023-10-21 15:59:31
我正在尝试获取mdY H:i格式的字符串并将其在数组中排序。我的排序代码是:    function orderDates($items) {    //Sort them. Latest one first    usort($items, function ($a, $b) {        $a = date('dmY H:i', strtotime($a));        $b = date('dmY H:i', strtotime($b));        if ($a == $b) {            return 0;        }        return ($a > $b) ? -1 : 1;    });    return $items;}我有一个测试用例:public function test_orderDates() {    $items = ["09082020 00:00", "12072020 00:00", "14062020 00:00", "17052020 00:00", "21062020 00:00", "24052020 00:00", "26072020 00:00"];    $rv = $this->cleanupFolder->orderDates($items);    $this->assertNotNull($rv);    $this->assertEquals(7, sizeOf($rv));    $this->assertEquals("09082020 00:00", $rv[0]);    $this->assertEquals("26072020 00:00", $rv[1]);    $this->assertEquals("12072020 00:00", $rv[2]);    $this->assertEquals("21062020 00:00", $rv[3]);    $this->assertEquals("14062020 00:00", $rv[4]);    $this->assertEquals("24052020 00:00", $rv[5]);    $this->assertEquals("17052020 00:00", $rv[6]);}我希望它按照这个顺序,但它只是以相同的顺序返回。我不明白我做错了什么。
查看完整描述

2 回答

?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

仔细看字符串 $a = date('dmY H:i', strtotime($a));


strtotime($a)正在尝试将字符串转换为时间戳。由于您有自定义日期格式,因此该字符串09082020 00:00将转换为false.


之后,date('dmY H:i', false)就会返回01011970 00:00。这就是排序不起作用的原因。


我会建议使用DateTime::createFromFormat.


    usort($items, function ($a, $b) {

        $a = DateTime::createFromFormat('dmY H:i', $a);

        $b = DateTime::createFromFormat('dmY H:i', $b);


        if ($a == $b) {

            return 0;

        }

        return ($a > $b) ? -1 : 1;

    });


查看完整回答
反对 回复 2023-10-21
?
慕侠2389804

TA贡献1719条经验 获得超6个赞

在这一部分


date('dmY H:i', strtotime($a));

date您正在尝试使用格式创建,但您设置了strtotime()返回 Unix 时间戳 (int) 的值。所以你可能正在寻找类似的东西:


\DateTime::createFromFormat('dmY H:i', $a);

所以它可能是这样的:


function orderDates($items) {

    //Sort them. Latest one first

    usort($items, function ($a, $b) {

        $a = \DateTime::createFromFormat('dmY H:i', $a);

        $b = \DateTime::createFromFormat('dmY H:i', $b);


        if ($a == $b) {

            return 0;

        }

        return ($a > $b) ? -1 : 1;

    });


    return $items;

}


查看完整回答
反对 回复 2023-10-21
  • 2 回答
  • 0 关注
  • 93 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信