【问题标题】:Laravel sort collection by dateLaravel 按日期排序集合
【发布时间】:2016-07-10 06:03:48
【问题描述】:

我有这个收集结果:

$result = [{
    "date": "2016-03-21",
    "total_earned": "101214.00"
},
{
    "date": "2016-03-22",
    "total_earned": "94334.00"
},
{
    "date": "2016-03-23",
    "total_earned": "96422.00"
},
{
    "date": "2016-02-23",
    "total_earned": 0
},
{
    "date": "2016-02-24",
    "total_earned": 0
},
{
    "date": "2016-02-25",
    "total_earned": 0
}]

我想按日期对结果进行排序:

$sorted = $transaction->sortBy('date')->values()->all();

但我没有得到预期的结果:

[{
    "date": "2016-02-23",
    "total_earned": 0

},
{
    "date": "2016-02-24",
    "total_earned": 0
},
{
    "date": "2016-02-25",
    "total_earned": 0
},
{
    "date": "2016-03-22",
    "total_earned": "94334.00"
},
{
    "date": "2016-03-21",
    "total_earned": "101214.00"
},
{
    "date": "2016-03-23",
    "total_earned": "96422.00"
}]

如您所见,第 2 个月的所有内容都已正确排序。然而在第 3 个月它开始搞砸了。 (实际结果比这更长,从第 3 个月开始就搞砸了)

有什么办法可以让它正确排序吗?

谢谢。

【问题讨论】:

  • date有什么类型的列?
  • @ChetanAmeta 嗨。日期类型是字符串
  • orderBy('date', 'ASC') 工作吗?
  • 嗨@AlexeyMezenin 我正在使用这种方法。 laravel.com/docs/5.2/collections#method-sortby 。我试过你的,但没有找到方法。谢谢

标签: php laravel


【解决方案1】:

使用sortBy() 尝试这样的事情:

$sorted = $transaction->sortBy(function($col) {
    return $col;
})->values()->all();

【讨论】:

  • 它有效!但我需要删除->date 才能使其正常工作。如果不是,它会返回给我trying to get property of non object
【解决方案2】:

我遇到了同样的问题。我创建了这个宏。

Collection::macro('sortByDate', function (string $column = 'created_at', bool $descending = true) {
/* @var $this Collection */
return $this->sortBy(function ($datum) use ($column) {
    return strtotime(((object)$datum)->$column);
}, SORT_REGULAR, $descending);

});

我是这样使用的:

$comments = $job->comments->merge($job->customer->comments)->sortByDate('created_at', true);

【讨论】:

  • 在我看来这是一个干净的解决方案。我在我的项目中使用了类似的解决方案:))
【解决方案3】:

你可以试试

$transaction->groupBy('date');

并确保 $transaction 是一个集合;

【讨论】:

  • 嗨,如果我将它分组,它将成为单独的数组。它没有排序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
相关资源
最近更新 更多