【问题标题】:Laravel sort collection by multi fieldsLaravel 按多字段排序集合
【发布时间】: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


    【解决方案1】:

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

    代替本节:

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

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 2021-06-27
      • 2013-09-10
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多