Laravel Collection sortBy函数出现问题



我正在尝试对集合执行多重排序,但似乎无法正常工作:

$myCollection = collect([
['foo' => 3, 'bar' => null, 'active' => 1],
['foo' => 2, 'bar' => null, 'active' => 1],
['foo' => 1, 'bar' => 1, 'active' => 1],
])->sortBy('foo')->sortBy('bar')->sortBy('active');

结果:

IlluminateSupportCollection {#417 ▼
#items: array:3 [▼
0 => array:3 [▼
"foo" => 3
"bar" => null
"active" => 1
]
1 => array:3 [▼
"foo" => 2
"bar" => null
"active" => 1
]
2 => array:3 [▼
"foo" => 1
"bar" => 1
"active" => 1
]
]
}

首先按活动正确排序(它们都相同=1(

然后按";条";(空<1(

然后sortBy('fo'(失败,因为(2<3(,但在2之前先显示3。。。预期结果:

IlluminateSupportCollection {#417 ▼
#items: array:3 [▼
0 => array:3 [▼
"foo" => 2
"bar" => null
"active" => 1
]
1 => array:3 [▼
"foo" => 3
"bar" => null
"active" => 1
]
2 => array:3 [▼
"foo" => 1
"bar" => 1
"active" => 1
]
]
}

这是我为演示做的一个样本。在我的真实场景中,我使用带有自定义函数回调的Collection::宏来比较日期。。。但即使在这个简单的例子中,事情看起来也不起作用。

您正在链接三种不同的排序,在这种情况下,您可以确保只正确完成了最后一次应用的排序。

所以尝试通过排序操作数组:

$myCollection = collect(...)->sortBy([
['foo', 'asc'],
['bar', 'asc'],
['active', 'asc'],
]);

您可以在文档中找到更多信息。

最新更新