2016-09-18 280 views
0

因此,我正在爲正在開發的項目開發一個消息系統,並且希望通過最新消息datetime組織一組對話。按數組值排序多維數組

這裏是我的數組:

Array(
    [0] = Array (
     [ID] => 1, 
     [USER] => 1, 
     [AUTHOR] => 2, 
     [TITLE] => Welcome to the Site!, 
     [DATETIME] => 2016-09-12 20:41:16, 
     [MESSAGES] => Array (
      [0] => Array (
       [ID] => 1, 
       [CONVERSATION] => 1, 
       [USER] => 1, 
       [CONTENT] => Welcome to the site User!, 
       [DATETIME] => 2016-09-13 00:19:20 
       ) 
      [1] => Array (
       [ID] => 2, 
       [CONVERSATION] => 1, 
       [USER] => 2, 
       [CONTENT] => Thanks for welcoming me!, 
       [DATETIME] => 2016-09-13 00:27:54 
       ) 
     ) 
    [1] = Array (
     [ID] => 2, 
     [USER] => 2, 
     [AUTHOR] => 1, 
     [TITLE] => Hello World!, 
     [DATETIME] => 2016-09-13 00:29:59, 
     [MESSAGES] => Array (
      [0] => Array (
       [ID] => 1, 
       [CONVERSATION] => 1, 
       [USER] => 1, 
       [CONTENT] => This is a test post., 
       [DATETIME] => 2016-09-13 00:19:45 
       ) 
      [1] => Array (
       [ID] => 2, 
       [CONVERSATION] => 1, 
       [USER] => 2, 
       [CONTENT] => This is an example response., 
       [DATETIME] => 2016-09-13 00:45:04 
       ) 
     ) 
) 

我想要做的是組織使用的是最新消息的日期時間談話的數組,以便與最新的消息談話會首先,與第二大部分的談話最近的消息將是第二個等等。我一直在尋找不同的功能,如

array_multisort 
array_sort 
usort 

我已經找到其他的解決方案在線,但他們不完全匹配什麼我在尋找因此,沒有人知道組織這些聊天信息的最佳方式?

+0

也許這有助於http://stackoverflow.com/questions/20805143/php-converting-multidimensional-array-to-modified-pre-order-traversal-tree –

+0

我不知道如何實現它到我的代碼, 能否請你幫忙? – Elxafil

回答

0

好了,所以搜索類似地雷和測試其他職位和修改代碼的年齡後,我找到了答案,我的解決方案:

$datetimes = array(); 
$recentDate = 0; 
foreach($conversations as $conversation) { 
    foreach($conversation["MESSAGES"] as $message) { 
     $curDate = strtotime($message["DATETIME"]); 
     if($curDate > $recentDate) { 
      $recentDate = $curDate; 
     } 
    } 
    $datetimes[] = $recentDate; 
} 
array_multisort($datetimes, SORT_DESC, $conversations); 

這個排序每個基於了與最近的消息談話的談話。