laravel - Laravel 按多字段排序集合
问题描述
我坚持根据不同情况在 laravel 中进行集合排序。
为简单起见,这里是一个示例集合:
1;
pmt: 1
thm: 1
customerFriendly: false
2;
pmt: 1
thm: 1
customerFriendly: true
3;
pmt: 2
thm: 4
customerFriendly: true
我需要先根据 pmt 值对这个集合进行排序。首先最低。如果有相同的 pmt 值,我需要根据 thm 值进行第二次排序。之后,如果可能有相同的 thm,我需要按客户布尔字段再次对其进行排序。
所以根据上面的例子,最终的排序列表应该是 2,1,3
据我所知,我可以先按 pmt 对列表进行排序,如果 thm 找到相同的 pmt-s,但我不能按 customerFriendly 对其进行排序。
这是我的代码:
$pmtDuplicated = $this->checkDuplicates($transformedLoans, 'pmt');
if ($pmtDuplicated) { //If we found same pmt-s sort by thm also
$secondSort = $transformedLoans->sortBy(function ($item) {
return $item->pmt . '-' . $item->thm;
})->values();
$thmDuplicatesInSecondSort = $this->checkDuplicates($secondSort, 'thm'); //Check again for same thm
if ($thmDuplicatesInSecondSort) { //If we found same thm sort by customerFriendly also
return $secondSort->sortBy('customerFriendly')->values();
} else {
return $secondSort;
}
} else {
return $transformedLoans->sortBy('pmt')->values();
}
有人可能可以帮助我吗?谢谢你。
解决方案
我找到了解决方案,如果以后对某人有帮助,我就把它留在这里。
而不是本节:
if ($thmDuplicatesInSecondSort) { //If we found same thm sort by customerFriendly also
return $secondSort->sortBy('customerFriendly')->values();
}
我需要使用这个:
if ($thmDuplicatesInSecondSort) { //Ha van THM alapján is egyezés akkor fogyasztóbarát alapján is rendezzen
return $secondSort->sortBy(function ($item) {
return $item->customerFriendly === false ? 1 : 0;
})->values();
}
推荐阅读
- python - 如何在 Python(Flask) 中模拟一个函数
- ruby-on-rails - 如何在rails中使用form_with和self join?
- android - Android kotlin - Navhost 片段 - 从菜单弹出
- macos - Mac 和 UWP 中 LibVLCSharp VideoView 的自定义渲染器 (Xamarin.Forms)
- javascript - 追加和填充下拉列表多个javascript
- python - 用python(Duffing振荡器)求解非线性非齐次微分方程
- colors - 仅特定页面中的wordpress css背景颜色
- python - 使用烧瓶从 python 调用 julia 返回错误
- javascript - 让组件显示已在 React 中循环的数据的最佳方式
- java - 我无法为数组索引赋值。我必须为各个变量赋值