Laravel Collection 多 key 排序

Laravel Collection 多 key 排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 测试数据
$data = [
[
'id' => 1,
'name' => '用户列表',
'sort' => 99,
'parent' => [
'name' => '用户管理',
'sort' => 10,
],
], [
'id' => 2,
'name' => '用户添加',
'sort' => 1,
'parent' => [
'name' => '用户管理',
'sort' => 10,
],
], [
'id' => 3,
'name' => '用户分类',
'sort' => 1,
'parent' => [
'name' => '用户管理',
'sort' => 10,
],
], [
'id' => 4,
'name' => '商品添加',
'sort' => 1,
'parent' => [
'name' => '商品管理',
'sort' => 5,
],
],
];

为每一条数据计算出一个权重值,然后根据这个权重值进行排序。

1
2
3
4
5
$data = collect($data)
->sortBy(function($item) {
return $item['parent']['sort'] * 100 + $item['sort'] . '.' . $item['id'];
})
->all();

往上