Laravel - 如何按不同键的时间戳值对数组对象进行排序?
I have this array of objects from a Laravel merged collection, accessed like this, $collection->values()->all()
, which returns the following:
[
{
"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"
}
}
]
I am trying to sort the order by the created_at
field, so it looks like this:
[
{
"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"
}
]
The issue is that created_at
is in two locations, sometimes it's under created_at
and other times it's under data.created_at
.
我有一个来自Laravel合并集合的这个对象数组,可以这样访问, 我试图通过 问题是 $ collection-> values() - > all() code>,返回以下内容: p>
[
{
“id”:“1”,
“ 键入“:”Teacher“,
”created_at“:”2017-05-11 18:00:00“
},
{
”id“:”2“,
”type“:”学生 “
”created_at“:”2017-05-11 15:00:00“
},
{
”id“:”3“,
”type“:”课程“,
”数据 “:{
”标题:“PHP”,
“created_at”:“2017-05-11 16:00:00”
}
}
]
code> pre> \ n
created_at code>字段对订单进行排序,所以它看起来像这样: p>
[
{\ n“id”:“1”,
“type”:“Teacher”,
“created_at”:“2017-05-11 18:00:00”
},
{
“id”: “3”,
“类型”:“课程”,
“数据”:{
“标题:”PHP“,
”created_at“:”2017-05-11 16:00:00“
}
},
{
“id”:“2”,
“type”:“Student”
“created_at”:“2017-05-11 15:00 :00“
}
]
code> pre>
created_at code>位于两个位置,有时位于
created_at下 code>,有时它在
data.created_at code>下。 p>
div>
I think you can use the sortByDesc
function:
$sorted = $collection->sortByDesc(function ($element) {
return $element->data ? $element->data->created_at : $element->created_at;
});