我正在嘗試創建一個包含投票和評論的活動源。兩個集合之間沒有任何關系。獲取評論:$CommentsCollection = $this->db->comments;$options = ['sort' => ['created' => -1], 'limit' => 15];$data = array ();$resultComments = $CommentsCollection->find($data, $options);要獲得選票:$VotesCollection = $this->db->votes;$options = ['sort' => ['created' => -1], 'limit' => 15];$data = array ();$resultVotes = $VotesCollection->find($data, $options);現在,我如何組合這兩個單獨的、不相關的集合結果并按創建(日期)對它們進行排序。我認為聚合或查找不是正確的方法,因為這兩個表不相關。我只想合并結果并按日期排序,以便我可以循環并將它們顯示在活動源上。
2 回答

慕慕森
TA貢獻1856條經驗 獲得超17個贊
我所做的是使用:
$finalArray = array_merge($resultComments, $resultVotes);
合并結果。然后按日期排序:
usort($finalArray, function($a, $b) { return strtotime($a['created']) - strtotime($b['created']); });
是我想多了。

牧羊人nacy
TA貢獻1862條經驗 獲得超7個贊
無需中間收集,有兩種方式。
unionWith
您可以從 4.4 版本開始使用-參考但如果你的收藏量很大的話我不推薦。
您應該在后端合并。發出兩個 http 請求并對結果進行排序。因為你得到了 30 條記錄,所以后端速度會很快。
- 2 回答
- 0 關注
- 151 瀏覽
添加回答
舉報
0/150
提交
取消