2016-03-02 61 views
0

排序根據日期陣列我需要根據日期使用PHP降序排序數組對象。我嘗試了下面的代碼,但沒有得到預期的結果。你能建議做這個任務嗎?提前致謝。如何降序

$document_list = array('01-14-2013', '01-12-2013', '04-05-2016'); 
usort($document_list, array($this, "sortByDate")); 

function sortByDate($a, $b) { 
    return strcmp($b['createdDate'], $a['createdDate']); 
} 

當我試着這個代碼,它得到錯誤的輸出。

+0

檢查[link](http://stackoverflow.com/questions/15557373/php-sort-array-by-date-value) – Yash

+0

使用'usort($ document_list,「sortByDate」);' – jitendrapurohit

回答

0

對於這種方法,你需要的日期格式&日期轉換爲時間戳。

$document_list = array('14-01-2013', '12-01-2013', '05-04-2016'); 
$document_list= array_map(function($v) { 
    return date('Y-m-d', strtotime($v)); 
}, $document_list); 

function sortByDate($a, $b) { 
    return strtotime($b) - strtotime($a); 
} 

usort($document_list, "sortByDate"); 

$document_list= array_map(function($v) { 
    return date('m-d-Y', strtotime($v)); 
}, $document_list); 

輸出

array(3) { 
    [0]=> 
    string(10) "04-05-2016" 
    [1]=> 
    string(10) "01-14-2013" 
    [2]=> 
    string(10) "01-12-2013" 
} 
+1

但你是在最終結果中更改整個日期格式?我相信數組元素的格式應該保持原樣。 – mitkosoft

+0

@mitkosoft。更新。 –

0
$document_list = array('01-14-2013', '01-12-2013', '04-05-2016'); 
usort($document_list, array($this, "sortByDate")); 

function sortByDate($a, $b) { 
    if(strtotime($b['createdDate'])<strtotime($a['createdDate'])){ 
     return $a['createdDate']; 
    }else{ 
     return $b['createdDate']; 
    } 
} 

嘗試此

0

喲可以做一些優雅像這樣使用:(usort:排序通過使用用戶定義的比較函數值的數組

<?php 
    // Sort the multidimensional array 
    usort($document_list, "custom_sort"); 
    // Define the custom sort function 
    function custom_sort($a,$b) { 
      return $a['some_sub_var']>$b['some_sub_var']; 
    } 
?> 
0

就我個人而言,由於日期時間格式的內部衝突,我發現按日期排序數組是一個不可擴展的選項。下面可能不會完全回答這個問題,但如果使用從數據庫中獲取的數組,則可能會有所幫助。

假設在你的桌子上有一個主要的自動遞增「ID」列,那麼你可以隨時ORDER BY id_column DESC。您將收到與按日期排序相同的結果 - 但速度要快得多。

如果由於某種原因,你無法通過SQL直接使用ORDER BY ID DESC,根據您的情況下通過these functions在PHP只是重組陣列。


補充說明:預覽以上PHP排序功能的實驗中,我強烈建議通過可視化等片段的陣列顯示器,我發現某處php.net上的郊區 -

function visual_arr($arr){ 
    echo '<pre>'; 
    print_r($arr); 
    echo '</pre>'; 
} 

調用它 - 只需在項目文件中的某處使用它:visual_arr($ the_array_you_want_to_display_in_human_radable_format)。顯然,選擇適合您的陣列^^

希望這有助於較短的名稱。