gpt4 book ai didi

php - 如何在 Laravel 5.1 中按多列对 Illuminate Collection 进行排序?

转载 作者:可可西里 更新时间:2023-11-01 12:25:20 26 4
gpt4 key购买 nike

我有一个 Laravel 的 Illuminate Collection 实例。该数组包含多个属性。

我需要能够根据 2 个不同的属性对集合进行排序。

我想先按名为“sort”的属性排序,然后按名为“title”的属性排序。

此外,我还有另一个集合,如果排序的值不为空,我喜欢按“排序”列对其进行排序,然后将“排序”值为空的项目打乱。

我怎样才能进行这种类型的排序?

最佳答案

您可以为 Collection::sort 提供回调函数:

$collection->sort(function($a, $b) {
if($a->sort === $b->sort) {
if($a->title === $b->title) {
return 0;
}
return $a->title < $b->title ? -1 : 1;
}
return $a->sort < $b->sort ? -1 : 1;
});

这已记录在案 here .

关于php - 如何在 Laravel 5.1 中按多列对 Illuminate Collection 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33713392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com