PHP如何按日期排序多维数组

5

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

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

我想将帖子按照最新日期到最旧日期排序,使其看起来像这样:
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
               ) 
);

我该如何对其进行排序?

4个回答

6
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

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

4
您可以使用Closureusort来实现这个功能:
usort($array, function($a, $b) {
    $a = strtotime($a[2]);
    $b = strtotime($b[2]);
    return (($a == $b) ? (0) : (($a > $b) ? (1) : (-1)));
});

2

我今天要离开办公桌,无法提供具体信息。但是这里有一个好的起点,其中包括示例:array_multisort


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

1
在你的代码周围添加一些解释会被认为是很好的做法。 - zx485

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接