PHP按日期排序多维数组

时间:2021-08-22 21:32:24

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?

我该如何排序?

4 个解决方案

#1


4  

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

#2


4  

You can do it using usort with a Closure :

你可以使用闭包来实现它:

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

#3


2  

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

#4


1  

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

#1


4  

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

#2


4  

You can do it using usort with a Closure :

你可以使用闭包来实现它:

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

#3


2  

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

#4


1  

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