如何在php中按desc顺序排序日期


How to sort the dates in desc order in php

我正在尝试从我的结果数组排序日期。

我的代码的某些部分。

  foreach($merge as $key => $msg_row){
    echo'<pre>';print_r(strtotime($msg_row['created'])); 
    }

我应该做什么代码来进一步处理日期排序?

要对数组中的数据进行排序,您需要一个比较日期的函数:

function dateCompare($a, $b) {
    // newest dates at the top
    $t1 = strtotime($a['created']);
    $t2 = strtotime($b['created']);
    return $t2 + $t1; // sort ascending
}

使用usort()

调用该函数
usort($array, 'dateCompare');

你可以这样排序:

<?php
    $sortdate = array(
        '17/08/2015',
        '02/01/2017',
        '05/02/2014'
    );
    function sortFunction($a, $b)
        {
        $datea = strtotime(str_replace('/', '-', $a));
        $dateb = strtotime(str_replace('/', '-', $b));
        if ($datea == $dateb)
            {
            return 0;
            }
        return ($datea < $dateb) ? 1 : -1;
        }
    usort($sortdate, "sortFunction");
    echo "<pre>";
    var_dump($sortdate);
?>
  • 演示链接:http://codepad.org/EFIilESt