PHP按日期对多维数组进行排序 [英] PHP sort multidimensional array by date

查看:119
本文介绍了PHP按日期对多维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题.我有一个多维数组,看起来像这样:

I'm having a problem. I have a multidimensional array, that looks like this:

Array ( [0] => 
              Array ( 
                    [0] => Testguy2's post. 
                    [1] => testguy2 
                    [2] => 2013-04-03 
              ) 

        [1] => Array ( 
                    [0] => Testguy's post. 
                    [1] => testguy 
                    [2] => 2013-04-07 
              ) 
);

我想按最新日期到最早的日期对帖子进行排序,所以看起来像这样:

I want to sort the posts from the newest date to the oldest date, so it looks like this:

Array ( [1] => Array ( 
                     [0] => Testguy's post. 
                     [1] => testguy 
                     [2] => 2013-04-07 
               ) 
        [0] => Array ( 
                     [0] => Testguy2's post. 
                     [1] => testguy2 
                     [2] => 2013-04-03
               ) 
);

如何对其进行排序?

推荐答案

function cmp($a, $b){

    $a = strtotime($a[2]);
    $b = strtotime($b[2]);

    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

usort($array, "cmp");

或者对于> = PHP 7

Or for >= PHP 7

usort($array, function($a, $b){
    return strtotime($a[2]) <=> strtotime($b[2]);
});

这篇关于PHP按日期对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆