2014-12-05 70 views
1

我試圖弄清楚如何對下面的數組進行排序,以便past數組項目被髮送到數組的最後,並按照start_date的降序排列。排序依賴於數組的數組

編輯。 Id可能在所有數組中包含時間數組鍵值項,以按start_date進行排序。

[216] => Array (
    [title] => Production 1 
    [start_date] => 20th Feb 
    [end_date] => 23rd Feb 2015 
    [ticket_link] => http://www.google.co.uk 
    [writer] => Sarah Ruhl 
    [thumb_image] => /files/3514/1762/4350/Biz-Bio-Pic.jpg 
    [past] => 1 
) 

[218] => Array(
    [title] => Production 3 
    [start_date] => 27th Feb 
    [end_date] => 2nd Mar 2015 
    [ticket_link] => www.google.co.uk 
    [writer] => Sarah Ruhl 
    [thumb_image] => /files/9414/1762/4351/Dan-Bio-Pic.jpg 
    [past] => 1 
) 

[219] => Array (
    [title] => Production 4 
    [start_date] => 3rd Mar 
    [end_date] => 5th Mar 2015 
    [ticket_link] => www.google.co.uk 
    [writer] => Sarah Ruhl 
    [thumb_image] => /files/4314/1762/4351/Kate-Bio-Pic.jpg 
    [past] => 0 
) 
+2

這個被問了很多,答案是'usort'。 – 2014-12-05 11:36:18

+1

[usort()](http://www.php.net/manual/en/function.usort.php)是你想要的功能。您需要按日期(時間戳或DateTime對象)而不是日期字符串進行比較,因此您需要在回調中進行轉換;你怎麼知道'start_date'指的是哪一年? – 2014-12-05 11:36:33

+0

@MarkBaker當我張貼如此編輯我的帖子時,我立刻注意到了這一點。我將使用'start_date'的時間戳。我已經格式化了當前的'start_date'值,因此獲得年份不是問題。我如何確保'past'項目也在數組的最後? – 2014-12-05 11:39:44

回答

2

試試這個 -

function checkdate($a, $b) 
{ 
    $a = strtotime($a['start_date']); 
    $b = strtotime($b['start_date']); 

    if ($a == $b) { 
     return 0; 
    } 

    return ($a > $b) ? -1 : 1; 
} 

function checkpast($a, $b) 
{ 
    $a_start = strtotime($a['start_date']); 
    $b_start = strtotime($b['start_date']); 

    if ($a_start == b_start) { 
     return ($a['past'] > $b['past']) ? -1 : 1; 
    } 

} 

$array = //your array 

usort($array, "checkdate"); 
usort($array, "checkpast"); 
+0

在按日期排序數組之前,我會如何排序過去的項目,以便它們位於數組的末尾? – 2014-12-05 11:42:38

+0

你如何定義過去的項目? – 2014-12-05 11:44:13

+0

其布爾值1過去0是當前 – 2014-12-05 12:06:53