我有这个数组作为Laravel Collection:
"data": [
{
"id": 863368,
"reference": "Ref 1",
"status": 1
},
{
"id": 863391,
"reference": "Ref 2",
"status": 2
},
{
"id": 863390,
"reference": "Ref 3",
"status": 2
},
{
"id": 863396,
"reference": "Ref 4",
"status": 3
}
];
我需要按status
而不是按asc
或对其进行排序desc
,但是具有状态的记录2
应首先在列表中,然后是状态,1
然后是状态3
。
我不知道如何实现这一目标,在此先感谢您。
嗨,有类似的问题,
$final = $collection->sortBy(function($item){
return array_search($item->status, ['2', '1', '3']);
});
['2', '1', '3']
(状态为2的状态为第一个,因为他的位置键为0,只需根据需要更改顺序即可。
或者您可以创建一个array
喜欢['2' => 1, '1' => 2, '3' => 3]
使用return $arry_of_order[$item->status];
(更快,然后array_search
每次调用)
PS:如果您可以使用DB(MySql)(如此处的其他人所建议的那样),则应坚持使用它, $query->orderByRaw("FIELD(status, '2', '1', '3')")
对于PostgreSQL,请看这里
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句