Skip to content
Advertisement

Sort Laravel Collection by custom order, other than asc or desc

I have this array as Laravel Collection :

"data": [
  {
    "id": 863368,
    "reference": "Ref 1",
    "status": 1
  },
  {
    "id": 863391,
    "reference": "Ref 2",
    "status": 2
  },
  {
    "id": 863390,
    "reference": "Ref 3",
    "status": 2
  },
  {
    "id": 863396,
    "reference": "Ref 4",
    "status": 3
  }
];

And I need to sort it by status, not by asc or desc, but the records with status 2 should be first on the list, then status 1 then status 3.

I can’t figure out how to achive this, thank you in advance.

Advertisement

Answer

Hi had similar issue,

$final = $collection->sortBy(function($item){
    return array_search($item->status, ['2', '1', '3']);
});

['2', '1', '3'] (Status with number 2 will be first because his position key is 0, just change the order as you need.

Or you can create an array like ['2' => 1, '1' => 2, '3' => 3]

use like return $arry_of_order[$item->status]; (faster then calling array_search each time)


P.S. If you can use Database (in case MySQL), as other people here suggested, you should stick to it, $query->orderByRaw("FIELD(status, '2', '1', '3')")

For PostgreSQL look here

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement