Laravel按多个字段对集合进行排序

时间:2020-04-07 14:20:27

标签: laravel sorting collections

我坚持根据不同情况在laravel中对集合进行排序。

为简单起见,下面是一个示例集合:

Object .fromEntries

我需要首先根据pmt值对该集合进行排序。最低优先。 如果有相同的pmt值,则需要根据thm值进行第二次排序。 在那之后,如果可能与我需要按客户布尔字段再次对它排序的主题相同。

因此,根据上面的示例,最终排序后的列表应为2,1,3

据我所知,我可以先按pmt对列表进行排序,如果thm找到相同的pmt-s,则无法按customerFriendly对其进行排序。

这是我的代码:

1;
 pmt: 1
 thm: 1
 customerFriendly: false
2;
 pmt: 1
 thm: 1
 customerFriendly: true
3;
 pmt: 2
 thm: 4
 customerFriendly: true

也许有人可以帮助我?谢谢。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,如果以后有人帮忙,我将其留在这里。

代替本节:

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

}

相关问题