简体   繁体   English

PHP 按日期排序多维数组

[英]PHP sort multidimensional array by date

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
               ) 
);

How do I sort it?我该如何排序?

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");

Or for >= PHP 7或者 >= PHP 7

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

You can do it using usort with a Closure :您可以使用带有Closure usort来做到这一点:

usort($array, function($a, $b) {
    $a = strtotime($a[2]);
    $b = strtotime($b[2]);
    return (($a == $b) ? (0) : (($a > $b) ? (1) : (-1)));
});

I'm just stepping away from my desk for the day so I can't offer specifics.我只是离开我的办公桌一天,所以我不能提供细节。 But here's a good place to get started that includes examples: array_multisort但这里是一个很好的开始,包括示例: array_multisort

$dates = array();       
foreach($a AS $val){
    $dates[] = strtotime($val[2]);
}
array_multisort($dates, SORT_ASC, $a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM