首页 > 解决方案 > 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();
                }

有人可能可以帮助我吗?谢谢你。

标签: laravelsortingcollections

解决方案


我找到了解决方案,如果以后对某人有帮助,我就把它留在这里。

而不是本节:

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();

}


推荐阅读