我希望能够按照特定顺序根据状态列对我的集合结果进行排序。
我的想法是对集合进行分页,但以特定顺序为优先级:[2, 1, ...],这样就可以先显示待处理列表,然后再显示其他列表!
是否有人知道这种方法?
提前感谢您。
我的想法是对集合进行分页,但以特定顺序为优先级:[2, 1, ...],这样就可以先显示待处理列表,然后再显示其他列表!
是否有人知道这种方法?
提前感谢您。
如果您的状态优先级不是按数字顺序排列的(例如,2> 1> 3> 0),您可以通过向sortBy传递回调函数来实现排序:
$collection = collect([
['name' => 'A', 'status' => 0],
['name' => 'B', 'status' => 3],
['name' => 'C', 'status' => 0],
['name' => 'D', 'status' => 1],
['name' => 'E', 'status' => 2],
['name' => 'F', 'status' => 1],
['name' => 'G', 'status' => 3],
['name' => 'H', 'status' => 1],
['name' => 'I', 'status' => 2],
['name' => 'J', 'status' => 3],
]);
// define status priority here
$statusPriorities = [2, 1, 3, 0];
$collection->sortBy(function($order) use($statusPriorities){
return array_search($order['status'], $statusPriorities);
})->values()->all();
输出:
[
[
"name" => "I",
"status" => 2,
],
[
"name" => "E",
"status" => 2,
],
[
"name" => "D",
"status" => 1,
],
[
"name" => "F",
"status" => 1,
],
[
"name" => "H",
"status" => 1,
],
[
"name" => "B",
"status" => 3,
],
[
"name" => "G",
"status" => 3,
],
[
"name" => "J",
"status" => 3,
],
[
"name" => "A",
"status" => 0,
],
[
"name" => "C",
"status" => 0,
],
]
in_array
函数,否则未找到的值将位于列表开头。 - undefined$tasks = App\Task::all();
$tasks1 = $tasks->sortBy('title');
return $tasks1->values()->all();
//values() method is used to preserve array original keys
//You can also user sortByDesc, to get reverse order of your collection.
[
{
"id": 5,
"title": "Akhtar",
"created_at": "2019-09-01 14:18:05",
"updated_at": "2019-09-01 14:18:05"
},
{
"id": 6,
"title": "Hamid khan",
"created_at": "2019-09-01 14:18:05",
"updated_at": "2019-09-01 19:19:18"
},
{
"id": 7,
"title": "Zarif",
"created_at": "2019-09-04 19:14:18",
"updated_at": "2019-09-04 19:14:18"
},
{
"id": 1,
"title": "testing",
"created_at": "2019-09-01 13:01:39",
"updated_at": "2019-09-01 13:01:39"
}
]