【问题标题】:Laravel - How to sort array objects by timestamp value of different keys?Laravel - 如何按不同键的时间戳值对数组对象进行排序?
【发布时间】:2017-05-18 19:28:50
【问题描述】:

我有这个来自 Laravel 合并集合的对象数组,像这样访问,$collection->values()->all(),它返回以下内容:

 [
  {
    "id": "1",
    "type": "Teacher",
    "created_at": "2017-05-11 18:00:00"
  },
  {
    "id": "2",
    "type": "Student"
    "created_at": "2017-05-11 15:00:00"
  },
  {
    "id": "3",
    "type": "Course",
    "data": {
       "title: "PHP",
       "created_at": "2017-05-11 16:00:00"
    }
  }
]

我正在尝试按created_at 字段对订单进行排序,所以它看起来像这样:

 [
  {
    "id": "1",
    "type": "Teacher",
    "created_at": "2017-05-11 18:00:00"
  },
  {
    "id": "3",
    "type": "Course",
    "data": {
       "title: "PHP",
       "created_at": "2017-05-11 16:00:00"
    }
  },
  {
    "id": "2",
    "type": "Student"
    "created_at": "2017-05-11 15:00:00"
  }
]

问题在于created_at 位于两个位置,有时位于created_at 下,有时位于data.created_at 下。

【问题讨论】:

  • 问题出在哪里?
  • @mimo 的回答正是你所需要的

标签: php arrays laravel laravel-5 laravel-collection


【解决方案1】:

我认为你可以使用sortByDescfunction:

$sorted = $collection->sortByDesc(function ($element) {
    return $element->data ? $element->data->created_at : $element->created_at;
});

【讨论】:

  • 切换到sortByDesc,因为作者要对日期进行降序排序。
猜你喜欢
  • 2018-07-16
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 2020-07-11
相关资源
最近更新 更多