通过最后保留null/empty对laravel集合进行排序 [英] Sorting laravel collection by leaving null/empty last
问题描述
似乎无法理解对laravel集合进行排序,因此empty
/null
数据最终将排在最后. (对usort有点困惑)
Can't seem to get my head around of sorting laravel collection so empty
/ null
data would end up being last. ( bit confused about usort )
我所拥有的几乎是一堆需要订购的times
/timestamps
.该列可能没有某些行.
Pretty much all I have is bunch of times
/ timestamps
that need to be ordered. Some rows may not have for that column.
我希望数据显示为ASC
/ascending
而最后显示empty/null
数据.
I would like data to appear ASC
/ ascending
while empty/null
data is shown last.
$collection->sortBy('timestamp')
排序很好,但是不知道如何处理空字段.
$collection->sortBy('timestamp')
sorts nicely but doesn't know how to deal with empty fields.
表看起来像这样.
$data = $data->sort(function($a, $b) use ($sortBy) {
if ($a->{$sortBy} and $b->{$sortBy}) return 0;
return ($a->{$sortBy} > $b->{$sortBy}) ? -1 : 1;
});
我在互联网上尝试过的随机代码,无法正常使用.
$sortBy
包含要按其排序的字段名称(因为它可能会更改)
错误的代码处理空/空数据,但顺序混乱.
Random code I tried from the internet, which I can't get to work correctly.
$sortBy
contains a field name to sort by ( since it may change )
Faulty code deals with empty / null data but its out of order.
推荐答案
尝试:
$collection->sortBy('-timestamp')
$collection->sortBy('-timestamp')
行得通吗?
这篇关于通过最后保留null/empty对laravel集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!