如何使用PHP中的sort函数按顺序列出数组的值

时间:2019-01-31 11:23:07

标签: php arrays loops sorting foreach

我有一个数组。数组内部的字符串值的示例为

10-01-2019
28-12-2018
16-01-2019
21-01-2019
14-11-2018

我需要按日期顺序列出这些内容。我无法根据它们的命名方式对它们进行排序,因为例如28-12-2018会被视为大于10-01-2019(因为28大于10),实际上却不是,因为第一个值是上一年的十二月。

因此,我进行了调整以将值显示为YYYYMMDD

20190110
20181228
20190116
20190121
20181114

但是,在遍历它们时我无法使这些值正确排序

//this is my array
$row['file_name'];

//remove hyphens from file name and display only 8 characters
$date = substr(str_replace("-", "", $row['sitma_file_name']), 0, 8);

//get the year part of $date
$year = substr($date,4);

//get the month part of $date
$month = substr($date,2, 2);

//get the day part of $date
$day = substr($date, 0, 2);

//concatenate above variables to make $date display as YYYYMMDD
$date = $year . $month . $day;

//put $date in an array
$date_array = array($date);

//sort the array
sort($date_array);

//loop through array and echo values 
foreach ($date_array as $value){
    echo $value;
}

预期结果是

20181114
20181228
20190110
20190116
20190121

但是实际结果是

20190110
20181114
20190116
20190121
20181228

1 个答案:

答案 0 :(得分:0)

这是解决方法:

$dates = [
    '10-01-2019',
'28-12-2018',
'16-01-2019',
'21-01-2019',
'14-11-2018'
    ];

usort($dates, function($a, $b){
    $dt1 = explode('-',$a);
    $dt2 = explode('-', $b);

    return ($dt2[2].$dt2[1].$dt2[0]) < ($dt1[2].$dt1[1].$dt1[0]);
});

echo '<pre>';
print_r($dates);

输出:

Array
(
    [0] => 14-11-2018
    [1] => 28-12-2018
    [2] => 10-01-2019
    [3] => 16-01-2019
    [4] => 21-01-2019
)