2016-08-15 166 views
0

我用于显示通知的最后一个数组是这样的:如何根据notif_date_sort对这个多维数组进行排序?

Array 
(
    [0] => Array 
     (
      [notification] => 1 new topic posted in : Current Affairs classroom 
      [on_create] => 12th Aug - 2016 5:20AM 
      [notif_date_sort] => 2016-08-12 05:20:23 
     ) 

    [1] => Array 
     (
      [notification] => 8 new topic posted in : GK classroom 
      [on_create] => 4th Aug - 2016 10:51AM 
      [notif_date_sort] => 2016-08-04 10:51:56 
     ) 
) 

我试着像multisort,ksort方法,但没有找到合适的结果。如何基于“notif_date_sort”对数组内的这些元素进行排序?

+2

[?排序与日期时间字符串的数组]的可能的复制(http://stackoverflow.com/questions/9095351/sorting-an-array-with-datetime-strings) – RomanPerekhrest

回答

0

你可以用你自己的功能usort()来排序结果日期

这样,

usort($array, 'custom_date_sort'); 
function custom_date_sort($a,$b) { 
    $date1 = DateTime::createFromFormat('Y-m-d H:i:s', $a["notif_date_sort"]); 
    $date2 = DateTime::createFromFormat('Y-m-d H:i:s', $b["notif_date_sort"]); 
    return $date1>$date2; 
} 

DateTime::createFromFormat创建一个从字符串的DateTime对象。

0

您需要使用usort()函数。

尝试这种情况:

function compare_dates($date1, $date2){ 
    $date1 = strtotime($date1['notif_date_sort']); 
    $date2 = strtotime($date2['notif_date_sort']); 
    if ($date1 == $date2) { 
     return 0; 
    } 
    return ($date2 < $date2) ? -1 : 1; 
} 

usort($array, "compare_dates"); 
相关问题