如何按自定义顺序对Laravel Collection进行排序(非升降序)
Got it! To get your Laravel Collection sorted in that custom status order (2 first, then 1, then 3), you can use the sortBy method with a simple priority mapping. Here's exactly how to do it:
Step 1: Define your priority order
First, create an array that assigns a numerical priority to each status. Lower numbers mean the item comes first:
$statusPriority = [ 2 => 0, // Status 2 gets highest priority (first) 1 => 1, // Status 1 comes next 3 => 2 // Status 3 is last ];
Step 2: Apply the custom sort to your collection
Use the sortBy method with a closure that looks up the priority for each item's status. If your data is an array of arrays (like your example), use the array key to access status:
// Your original collection $collection = collect([ ["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] ]); // Sort using the priority map $sortedCollection = $collection->sortBy(function ($item) use ($statusPriority) { return $statusPriority[$item['status']]; });
If you're working with Eloquent models (where status is a property instead of an array key), just change $item['status'] to $item->status.
Step 3: Reindex the collection (optional)
By default, sortBy preserves the original keys of the collection. If you want a fresh, sequential index, chain the values() method:
$sortedCollection = $collection->sortBy(function ($item) use ($statusPriority) { return $statusPriority[$item['status']]; })->values();
What the result looks like
After sorting, your collection will be ordered exactly as you wanted:
- Items with status 2 (Ref 2 and Ref 3)
- Item with status 1 (Ref 1)
- Item with status 3 (Ref 4)
This approach is super flexible—if you ever need to adjust the order later, just update the $statusPriority array and you're good to go!
内容的提问来源于stack exchange,提问作者Dwix

