2013-04-07 171 views
5

我遇到问题。我有一个多维数组,看起来像这样:PHP按日期排序多维数组

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

这工作得很好...... – 2017-02-20 09:39:58

2

我只是离开我的办公桌,所以我不能提供具体细节。但这里的上手包括实例的好去处:array_multisort

4

你可以做到这一点使用usortClosure

usort($array, function($a, $b) { 
    $a = strtotime($a[2]); 
    $b = strtotime($b[2]); 
    return (($a == $b) ? (0) : (($a > $b) ? (1) : (-1))); 
}); 
1
$dates = array();  
foreach($a AS $val){ 
    $dates[] = strtotime($val[2]); 
} 
array_multisort($dates, SORT_ASC, $a); 
+0

这会被认为是好的在代码中添加一些解释。 – zx485 2016-09-17 08:37:26