You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按自定义顺序对Laravel Collection进行排序(非升降序)

Custom Sorting Laravel Collection by Status Order

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:

  1. Items with status 2 (Ref 2 and Ref 3)
  2. Item with status 1 (Ref 1)
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:44:44