Sorting laravel collection by leaving null/empty last

一曲冷凌霜 提交于 2019-12-11 05:25:20

问题


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 )

Pretty much all I have is bunch of times / timestamps that need to be ordered. Some rows may not have for that column.

I would like data to appear ASC / ascending while empty/null data is shown last.

$collection->sortBy('timestamp') sorts nicely but doesn't know how to deal with empty fields.

Table looks like this.

   $data = $data->sort(function($a, $b) use ($sortBy) {
        if ($a->{$sortBy} and $b->{$sortBy}) return 0; 
        return ($a->{$sortBy} > $b->{$sortBy}) ? -1 : 1;
    }); 

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.


回答1:


Try:

$collection->sortBy('-timestamp')

Does it work?




回答2:


Have to use sort() with a closure. Below will sort timestamp ASC with NULL at the end.

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

    return $a->timestamp < $b->timestamp ? -1 : 1;
});



回答3:


I assume your timestamp is unix timestamp.

You can sort it like this :

$sorted = $collection->sortByDesc('timestamp');


来源:https://stackoverflow.com/questions/43449707/sorting-laravel-collection-by-leaving-null-empty-last

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!