通过将 null/empty 留在最后对 laravel 集合进行排序

Sorting laravel collection by leaving null/empty last

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

我几乎只有一堆 times / timestamps 需要订购。该列可能没有某些行。

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

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

Table 看起来像这样。

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

我从互联网上试过的随机代码,我无法正常工作。 $sortBy 包含排序依据的字段名称(因为它可能会更改) 错误代码处理空/空数据,但它是乱序的。

我假设你的 timestamp 是 unix 时间戳。

你可以这样排序:

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

尝试:

$collection->sortBy('-timestamp')

有效吗?

必须使用带闭包的 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;
});

我遇到了类似的问题。在我的例子中,$resulttime 属性可能是 NULL。它的行为就好像 NULL0(如 int),这是预期的行为。但我也想通过将 NULL 留在最后来对集合进行排序。

$collection->sortBy(function ($result) {
    if ($result['time'] === NULL) {
        return PHP_INT_MAX;
    }

    return $result['time'];
});

您只需返回一个按字母顺序排列的比数组中所有其他值更高的值即可实现此目的。即 PHP_INT_MAX 是安全的。这将确保 time 等于 NULL 的所有结果都在数组的末尾。

类似于 ,但更短 PHP 7.4+ 版本:

$collection->sortBy(fn($e) => $e->timestamp ?: PHP_INT_MAX)