Laravel - 如何根据不同键的时间戳值对数组对象进行排序?

Laravel - How to sort array objects by timestamp value of different keys?

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

 [
  {
    "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.

我想你可以使用sortByDesc功能:

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