【发布时间】:2020-07-19 18:33:02
【问题描述】:
我坚持在 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();
}
也许有人可以帮助我吗?谢谢。
【问题讨论】:
标签: laravel sorting collections