【问题标题】:Laravel collections not sortingLaravel 集合不排序
【发布时间】:2017-06-06 15:20:36
【问题描述】:

我有以下 Eloquent 合集:

[
    [
        'id' => 60902,
        'source' => 'M',
        'price'  => 10.15
    ],
    [
        'id' => 57348,
        'source' => 'A',
        'price'  => 12.00
    ],
    [
        'id' => 54472,
        'source' => 'A',
        'price'  => 12.00
    ],
]

我正在尝试使用以下代码对其进行排序:

$items = $items->sort(function (Item $a, Item $b) {
    if ($a->source == 'A') {
        if ($b->source == 'M' || ($b->source == 'A' && $a->price < $b->price)) {
            return 1;
        } elseif ($b->source == 'A' && $a->price == $b->price) {
            return 0;
        } else {
            return -1;
        }
    } else {
        if ($b->source == 'A' || ($b->source == 'M' && $b->price < $a->price)) {
            return -1;
        } elseif ($b->source == 'M' && $b->price == $a->price) {
            return 0;
        } else {
            return 1;
        }
    }
});

但是,$items 的原始排序顺序在前后始终相同。列表中的第一项 (60902) 应该已从开头移到结尾。

我运行了 Xdebug 跟踪,可以看到在排序函数中第 60902 项返回 -1,而其他两项返回 0,因为它们是等价的。

这就是我希望集合在排序后的样子:

[
    [
        'id' => 57348,
        'source' => 'A',
        'price'  => 12.00
    ],
    [
        'id' => 54472,
        'source' => 'A',
        'price'  => 12.00
    ],
    [
        'id' => 60902,
        'source' => 'M',
        'price'  => 10.15
    ]
]

我的逻辑哪里搞砸了?

【问题讨论】:

  • 你想做什么?按价格排序并按 desc 排序?
  • 我正在按来源和价格进行复杂的排序。来源 A 比来源 M 更受欢迎。如果来源相同,价格越低越好。
  • 我知道这不是您要问的,但是假设您从数据库中获取结果,为什么不在数据库查询级别对结果进行排序呢? ORDER BY source, price 应该这样做。
  • 我简化了这篇文章的结果。第一项之后的所有内容都是其他查询结果的合并结果。价格价值仅来自关系。由于记录的数量和需要进行这种排序的罕见性,这样做是为了提高效率。有时我需要在关系中调用save(),因此将它们分开很方便。否则,我会同意。

标签: laravel sorting collections laravel-5.3


【解决方案1】:

解决这个问题的方法非常简单......我只需要在返回排序值时交换 1-1 即可获得我想要的结果。

新代码如下所示:

$items = $items->sort(function (Item $a, Item $b) {
    if ($a->source == 'A') {
        if ($b->source == 'M' || ($b->source == 'A' && $a->price < $b->price)) {
            return -1;
        } elseif ($b->source == 'A' && $a->price == $b->price) {
            return 0;
        } else {
            return 1;
        }
    } else {
        if ($b->source == 'A' || ($b->source == 'M' && $b->price < $a->price)) {
            return 1;
        } elseif ($b->source == 'M' && $b->price == $a->price) {
            return 0;
        } else {
            return -1;
        }
    }
});

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 2020-01-04
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2017-10-05
    • 2015-08-23
    • 2020-07-19
    相关资源
    最近更新 更多