我有一个来自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
下。
我认为您可以使用sortByDesc
函数:
$sorted = $collection->sortByDesc(function ($element) {
return $element->data ? $element->data->created_at : $element->created_at;
});