I have two different objects with different columns in DB. Since I need to show both of those objects on timeline, I wanted to merge them and sort by date. Date column is not called the same so I am adding it within for loop.
public function index()
{
$users = array_slice(WPUser::orderBy('id', 'desc')->get()->toArray(), 0, 20);
// count = 80
$comments = WPComment::with('recipe')->orderBy('comment_date', 'desc')->get()->toArray();
foreach ($comments as &$comment) {
$comment['date_time'] = $comment['comment_date'];
}
// count = 241
$favorites = WPFavorite::with('user', 'recipe')->orderBy('date_time', 'desc')->get()->toArray();
// count = 321
$mergedArray = array_merge_recursive($comments, $favorites);
$mergedArray = collect($mergedArray);
$mergedArray = $mergedArray->sortByDesc('date_time');
$mergedArray = $mergedArray->groupBy('date_time');
return $mergedArray;
//return view('dashboard.index', compact('users', 'mergedArray'));
}
The problem is that I can't get what I want. If I leave dates to be of default Carbon format, they seem to sort fine, but they will not group by day of course because of different h:m:s. If I however change that in both models:
public function getDateTimeAttribute($date)
{
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d.m.Y.');
}
I am not getting it sorted right...
I tried by grouping the objects before even converting them to array which then gives me back sorted arrays, but such that I have first object sorted, and then merged to it below second object...
If I have both Comment and Favorite posted on same date (for example today), I want them both on top of my JSON file under '02.09.2016'
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)