如何在PHP中对数组中的日期进行排序? [重复]

问题描述 投票:0回答:2
Array
(
    [0] => 01_January_2020
    [1] => 02_December_2019
    [2] => 02_January_2020
    [3] => 03_December_2019
    [4] => 03_January_2020
    [5] => 04_December_2019
    [6] => 04_January_2020
    [7] => 05_December_2019
    [8] => 05_January_2020
    [9] => 06_December_2019
    [10] => 06_January_2020
    [11] => 07_December_2019
    [12] => 07_January_2020
    [13] => 08_December_2019
    [14] => 08_January_2020
    [15] => 09_December_2019
    [16] => 09_January_2020
    [17] => 10_December_2019
    [18] => 10_January_2020
    [19] => 11_December_2019
    [20] => 11_January_2020
    [21] => 12_December_2019
    [22] => 12_January_2020
    [23] => 13_December_2019
    [24] => 13_January_2020
    [25] => 14_December_2019
    [26] => 14_January_2020
    [27] => 15_December_2019
    [28] => 15_January_2020
    [29] => 16_December_2019
    [30] => 16_January_2020
    [31] => 17_December_2019
    [32] => 17_January_2020
    [33] => 18_December_2019
    [34] => 18_January_2020
    [35] => 19_December_2019
    [36] => 19_January_2020
    [37] => 20_December_2019
    [38] => 20_January_2020
    [39] => 21_December_2019
    [40] => 22_December_2019
    [41] => 23_December_2019
    [42] => 24_December_2019
    [43] => 25_December_2019
    [44] => 26_December_2019
    [45] => 27_December_2019
    [46] => 28_December_2019
    [47] => 29_December_2019
    [48] => 30_December_2019
    [49] => 31_December_2019
)

这是我的数组,我想按月份和日期排序

01_December_2019
02_December_2019.. 
and all

我尝试了很多方法,但没有得到任何结果。谁能帮我解决这个问题吗?

php arrays date
2个回答
0
投票

您可以使用

usort()
和从该格式创建日期时间对象的回调来创建自己的排序函数(因为
d_F_Y
不是可识别的格式,您必须使用
createFromFormat()
)。一旦有了正确的日期时间对象,就可以比较它们,并将它们按正确的顺序排列(通过比较时间戳可以轻松完成,
format("U")
)。

usort($yourArray, function($a, $b) {
    $format = "d_F_Y";
    $a = DateTime::createFromFormat($format, $a);
    $b = DateTime::createFromFormat($format, $b);
    return $a->format("U") - $b->format("U");
});

0
投票

$arr_dates
是你的日期数组

$final_date = array();
foreach ($arr_dates as $str_date) {
    /* to remove underscore ( _ ) */
    $date = str_replace('_', ' ', $str_date); 
    $final_date[strtotime($date)] = $date;
}
ksort($final_date);
echo '<pre>';
print_r($final_date);

希望这对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.