2014-08-30 55 views
1

如何合併來自同一實體的2個結果並按日期排序?合併來自同一個實體的2個結果

我此刻剛剛驗證碼:

$conversations1 = $this->getDoctrine() 
          ->getManager() 
          ->getRepository('AcmeMessageBundle:Conversation') 
          ->getConversations($this->getUser()->getId(), $current); 

    $conversations2 = $this->getDoctrine() 
          ->getManager() 
          ->getRepository('AcmeAdosMessageBundle:Conversation') 
          ->getConversationsInverse($this->getUser()->getId(),$current); 

但是如果我合併的對話1個保護2日期不會正確排序。有沒有簡單的方法來合併和按日期排序?

我有任何想法如何做到這一點。

編輯我的解決方案

$conversations1 = $this->getDoctrine() 
         ->getManager() 
         ->getRepository('AcmeMessageBundle:Conversation') 
         ->getMoreConversations($this->getUser()->getId(), $current, $conversation->getDate()->format('Y-m-d H:i:s')); 

$conversations2 = $this->getDoctrine() 
         ->getManager() 
         ->getRepository('AcmeMessageBundle:Conversation') 
         ->getMoreConversationsInverse($this->getUser()->getId(), $current, $conversation->getDate()->format('Y-m-d H:i:s')); 

$conversations = array(); 
foreach (array_merge($conversations1, $conversations2) as $conversation) { 
    $conversations[$conversation->getDate()->format('Y-m-d H:i:s')] = $conversation; 
} 

krsort($conversations); 
+0

你能澄清你的意思是「合併」嗎?你想用另一個對象的屬性來更新一個對象的屬性嗎?你想要一組對話對象嗎?還有別的嗎? – 2014-08-30 15:58:19

+0

不,不是,它只是用來顯示對話列表。但爲了獲得所有對話,我必須提出兩個疑問。對話需要按日期排序。所以如果我有理由做一個array_merge();這不是按日期排序。這將是這樣的秩序:conversations1_30may,conversation1_25may,conversation2_28may,conversation2_22may。我需要這樣的命令:conversations1_30may,conversation2_28may,conversation1_25may,conversation2_22may。所以我想問一下在教條中是否有辦法,或者是否有人爲此寫了一個腳本。 – Hotgeart 2014-08-30 16:40:40

回答

2

認爲您可以在2個數組合併成一個ArrayCollection,然後那種(通過製作成一個迭代器和背部的方式再次)。

$merged = new ArrayCollection(
    array_merge(
     $conversations1, 
     $conversations2 
    ) 
); 

$iterator = $merged->getIterator(); 

$iterator->uasort(function ($a, $b) { 
    return ($a->getDate() < $b->getDate()) ? -1 : 1; 
}); 

$conversations = new ArrayCollection(iterator_to_array($iterator)); 

這幾乎不是討論事情的最好方式,但它可能是正常的。

注意這是從一堆不同的答案拼湊在一起,所以我不確定實際結果的質量。

+0

謝謝,我混合你的解決方案 – Hotgeart 2014-08-30 23:56:03

1

通過在單個SQL語句中檢索所有對話(使用SORT BY選項),查詢本身中排序對象的最佳方式將在查詢本身中進行。數據庫在排序結果時非常高效。如果你不能在你的版本庫代碼中做到這一點,不管出於何種原因,迭代器(上面提到的)都是一個聰明的解決方案。一個更簡單的方法是構造一個對話數組,其中對話日期是數組索引,以便對結果進行排序。所以像這樣的一個基本的例子:

$conversations = array(); 
foreach (array_merge($conversations1, $conversations2) as $conversation) { 
    $conversations[$conversation->getDate()] = $conversation; 
} 
sort($conversations); 

這應該產生一個日期排序的Conversation對象數組。由於教義返回一個對象數組,您必須遍歷該列表來構造您的對話數組。

+0

謝謝你,我混合你的解決方案 – Hotgeart 2014-08-30 23:57:34

相關問題