I'm trying to combine and sort the results from several db queries.
$events = collect();
$downedEvents = EventDowned::where('mission', $missionId)
->orderBy('mission_time', 'asc')
->get();
$events->push($downedEvents);
$getInOutEvents = EventGetInOut::where('mission', $missionId)
->orderBy('mission_time', 'asc')
->get();
$events->push($getInOutEvents);
$missileEvents = EventMissile::where('mission', $missionId)
->orderBy('mission_time', 'asc')
->get();
$events->push($missileEvents);
$flattenedEvents = $events->flatten();
$sortedEvents = $flattenedEvents->sortBy('mission_time');
return $sortedEvents->all();
The result looks like this:
As you can see it has correctly combined the results, however they remain in their original query order, not sorted.
I've also tried
$sortedEvents = $flattenedEvents->sortBy(function($event) {
return (int) $event->mission_time;
});
To extend on @Titan's answer, i guess the extensions/ postman maintain the array indexing order. Not really sure.
To get rid of that
return $collection->values();
Here is an example
$arr = collect([
0 => [
'name' => 'foo',
'weight' => 70
],
1 => [
'name' => 'bar',
'weight' => 80
]
]);
return $arr->sortByDesc('weight');
the extension will still keep the index order
return $arr->sortByDesc('weight')->values();
This will get the desired order.
A huge fail on my part, my pretty print JSON chrome extension was messing with the display order, viewing the raw response showed they were in fact sorted correctly... ::facepalm::
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With