第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

usort 將字符串轉(zhuǎn)換為日期

usort 將字符串轉(zhuǎn)換為日期

PHP
斯蒂芬大帝 2023-10-21 15:59:31
我正在嘗試獲取mdY H:i格式的字符串并將其在數(shù)組中排序。我的排序代碼是:    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;}我有一個(gè)測試用例: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]);}我希望它按照這個(gè)順序,但它只是以相同的順序返回。我不明白我做錯(cuò)了什么。
查看完整描述

2 回答

?
吃雞游戲

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊

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


strtotime($a)正在嘗試將字符串轉(zhuǎn)換為時(shí)間戳。由于您有自定義日期格式,因此該字符串09082020 00:00將轉(zhuǎn)換為false.


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


我會(huì)建議使用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;

    });


查看完整回答
反對 回復(fù) 2023-10-21
?
慕俠2389804

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊

在這一部分


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

date您正在嘗試使用格式創(chuàng)建,但您設(shè)置了strtotime()返回 Unix 時(shí)間戳 (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;

}


查看完整回答
反對 回復(fù) 2023-10-21
  • 2 回答
  • 0 關(guān)注
  • 179 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號