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

时间:2017-05-18 19:28:50

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

我有来自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之下。

1 个答案:

答案 0 :(得分:4)

我认为您可以使用sortByDesc功能:

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