2017-02-21 44 views
0

所以我有一個二維數組,看起來有點像這樣:如何通過主日期鍵和二級字母數字在PHP排序

[0] => Array(
    [date] => 23-01-2017 
    [name] => bbb 
    [othertext] => text2 
) 
[1] => Array(
    [date] => 23-01-2017 
    [name] => aaa 
    [othertext] => text3 
) 
[2] => Array(
    [date] => 24-01-2017 
    [name] => aaa 
    [othertext] => text1 
) 

注:這個問題沒有標記爲MySQL中,所使用的數據庫是MongoDB,排序類型爲'date' => 'asc'

目前這是從我的數據庫按日期排序返回,但沒有考慮名稱屬性。我想現在通過date對此進行排序,對於相同日期的條目,然後按name排序。

我目前的做法是在其上運行的數據的array_multisort

array_multisort(
    $array['date'], SORT_STRING, 
    $array['name'], SORT_STRING, 
    $arrayCopy //<--This copy of the array has the full datetime object 
); 

但這然後排序日期作爲字符串,所以在某些情況下它正確排序它;例如1st March會在2nd Feb之前。如果將月份放在首位,那麼當Dec/Jan日期排序時它會錯誤排序。

這是什麼方法?我見過提到usort(),但我不確定如何在這個用例中實現它。 array_multisort是否具有日期功能?

+0

Simp在你的SQL查詢中加入這種排序'ORDER BY date ASC,name ASC' –

+0

http://stackoverflow.com/questions/2910611/php-sort-a-multidimensional-array-by-element-containing-date –

+0

@ Ayaou這個問題沒有被標記爲MySQL,它使用了一個MongoDB數據庫 - 我已經擴展了這個問題來指定它。 :) – user3420034

回答

1

在你的數據庫查詢:

SELECT * from `your_table_name` order by date asc, name asc; 

也許這MongoDB中:

$cursor->sort(array('date' => 1, 'name' => 1)); 

參見:http://php.net/manual/en/mongocursor.sort.php

不需要做它在PHP之後。

+0

這個問題沒有被標記爲MySQL,它使用MongoDB數據庫 - 我已經擴大了問題指定這個。 :) – user3420034

+1

更新了我的答案 – Tschallacka

1

我強烈建議通過數據庫來做到這一點。

但是如果你必須使用usort或試圖瞭解它是如何工作的:

$arr = [ 
    [ 
     'date' => '23-01-2017', 
     'name' => 'bbb', 
    ], 
    [ 
     'date' => '23-01-2017', 
     'name' => 'aaa', 
    ], 
    [ 
     'date' => '24-01-2017', 
     'name' => 'aaa', 
    ], 
]; 

function cmp($a, $b) 
{ 
    $aDate = DateTime::createFromFormat('d-m-Y', $a['date']); 
    $bDate = DateTime::createFromFormat('d-m-Y', $b['date']); 


    if ($aDate == $bDate) { 
     if ($a['name'] == $b['name']) { 
      return 0; 
     } 
     return ($a['name'] < $b['name']) ? -1 : 1; 
    } 
    return ($aDate < $bDate) ? -1 : 1; 
} 

usort($arr, "cmp"); 

print_r($arr); 

http://php.net/manual/en/function.usort.php

輸出:

[0] => Array 
    (
     [date] => 23-01-2017 
     [name] => aaa 
    ) 

[1] => Array 
    (
     [date] => 23-01-2017 
     [name] => bbb 
    ) 

[2] => Array 
    (
     [date] => 24-01-2017 
     [name] => aaa 
    ) 
1

隨着usort功能,你可以這樣做:

$foo = array(
    0 => array(
    "date" => "23-01-2017", 
    "name" => "bbb", 
    "othertext" => "text2" 
), 
    1 => array(
    "date" => "23-01-2017", 
    "name" => "aaa", 
    "othertext" => "text3" 
), 
    2 => array(
    "date" => "24-01-2017", 
    "name" => "aaa", 
    "othertext" => "text1" 
) 
); 

usort($foo, function($a, $b) 
{ 
    return $a["date"] === $b["date"] ? strcmp($a["name"], $b["name"]) : strcmp(strtotime($a["date"]), strtotime($b["date"])); 
}); 

var_dump($foo);