通过最后留空/空来对 Laravel 集合进行排序

m4g*_*ix1 2 php collections usort laravel

似乎无法理解对 laravel 集合进行排序的问题,因此empty/null数据最终会排在最后。(对 usort 有点困惑)

我所拥有的几乎就是一堆times/timestamps需要订购的东西。某些行可能没有该列。

我希望数据出现ASC/ascendingempty/null数据最后显示。

$collection->sortBy('timestamp') 排序很好,但不知道如何处理空字段。

数据

表看起来像这样。

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

我从互联网上尝试的随机代码,但无法正常工作。 $sortBy包含要排序的字段名称(因为它可能会更改) 错误代码处理空/空数据,但其顺序不正确。 有毛病

小智 6

必须将 sort() 与闭包一起使用。下面将以 NULL 结尾对时间戳 ASC 进行排序。

$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;
});
Run Code Online (Sandbox Code Playgroud)