17

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:

ss

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;
});
Titan
  • 5,567
  • 9
  • 55
  • 90
  • That would work if the items are associative arrays, provide your callback function to `sortBy` and try. https://laravel.com/docs/5.4/collections#method-sortby – Shady Atef Mar 12 '17 at 22:47
  • I've tried `$sortedEvents = $flattenedEvents->sortBy(function($event) { return $event->mission_time; });` but it has the same result – Titan Mar 12 '17 at 22:50
  • var_dump `$event->mission_time` and check the type – Shady Atef Mar 12 '17 at 23:26
  • I thought that might be the case so I did try `return (int) $event->mission_time` with the same result – Titan Mar 13 '17 at 07:33
  • It seems right for me.. the only thing I can say is to debug it.. set breakpoints and dive deep into the `sortBy` code. Don't worry it's a function of 10 lines. not a big deal – Shady Atef Mar 13 '17 at 14:04
  • @ShadyAtef found the issue (see answer) sorry for wasting your time :( – Titan Mar 13 '17 at 19:33

2 Answers2

34

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.

f_i
  • 3,084
  • 28
  • 31
  • 4
    this should be marked as correct answer! you saved my day dude! – Merkurial Sep 02 '19 at 09:17
  • 2
    That is it! 10th time that I've been here. Now its memorized, I promise! – Jonathan Martins Mar 13 '20 at 19:48
  • This worked. Thank you! I came acoss a weird issue: If I save the sorted values again in the same field of the collection, the order was lost again. When I temporarely saved the sorted values in a variable, and unset the field before saving the variable in it again, it worked. – rissom Sep 21 '22 at 15:02
30

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::

Titan
  • 5,567
  • 9
  • 55
  • 90
  • I will go back calmly to my AI study., But Good luck that you found it. – Shady Atef Mar 13 '17 at 19:35
  • 6
    Lmao this saved me... Why would it do that!? – Traxo Apr 28 '18 at 17:07
  • 1
    @Titan Really, that was the problem ?, Why do I have exactly the same problem and I have been trying to make the order work for hours and I have not managed any idea or recommendation? please – FeRcHo Sep 21 '18 at 21:09
  • 2
    I experienced the same issue with Postman... The pretty response was not ordered and the Raw response was ordered like I wanted ! Thanks – Jicao Mar 05 '19 at 11:38
  • 1
    Was pulling my hair out on this! For anyone reading, "JSON Formatter" for Chrome does this. Thank you! – Giovanni S Jul 05 '21 at 22:27