2017-05-18 23 views
0

我有这样的阵列从Laravel对象合并征收,这样的访问,$collection->values()->all(),它返回如下:Laravel - 如何通过不同键的时间戳值对数组对象进行排序?

[ 
    { 
    "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下。

+0

什么问题呢? –

+0

@ mimo的答案正是你所需要的 – Sandeesh

回答

4

我想你可以使用sortByDesc功能:

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

切换到'sortByDesc',因为作者想按降序对日期进行排序。 – Sandeesh

+0

谢谢@Sandeesh,更新了我的回答 – mimo

+0

很棒,谢谢:) – Wonka

相关问题