当我尝试通过默认sort()
函数对Laravel集合进行排序时-我得到了正确的排序。但是,当我尝试通过Ajax获取此数据时-我收到来自Ajax响应的无效排序。
例如:
$a = collect([
'2019-01-10',
'2019-01-01',
'2019-01-24',
'2019-01-03',
'2019-01-02'
])->sort();
Laravel dd($a)
给了我正确的排序:
Collection {#508
#items: array:5 [
1 => "2019-01-01"
4 => "2019-01-02"
3 => "2019-01-03"
0 => "2019-01-10"
2 => "2019-01-24"
]
}
但是当我尝试为jQuery Ajax请求返回此数据时:
return response()->json([$a]);
console.log()
的ajax响应:
0: "2019-01-10"
1: "2019-01-01"
2: "2019-01-24"
3: "2019-01-03"
4: "2019-01-02"
无效的订购
更新
我有比示例更复杂的数据:
首先,我得到了项目清单:
$projects = DB::table('projects')
->whereIn(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"), $dates)
->orderBy('created_at', 'DESC')
->get();
接下来,我按created_at分组:
$data = $projects->groupBy(function ($project) {
return Carbon::parse($project->created_at)->format('Y-m-d');
})->sortKeysDesc(); //<----- sort to display newest first
所以我的结果数组排序正确,如下所示:
[
'2019-01-20' => [...] nested arrays
'2019-01-15' => [...] nested arrays
'2019-01-10' => [...] nested arrays
]
但是JS从Ajax返回:
[
'2019-01-10' => [...] nested arrays
'2019-01-15' => [...] nested arrays
'2019-01-20' => [...] nested arrays
]
答案 0 :(得分:0)
尝试以下代码:
$items = array_values($a->toArray());
return response()->json([$items]);
答案 1 :(得分:0)
为确保保留顺序,应在集合上使用toArray()
中的内置功能。</ p>
return response()->json($a->toArray());
答案 2 :(得分:0)
使用->values()
摆脱阵列键。
$a = collect([
'2019-01-10',
'2019-01-01',
'2019-01-24',
'2019-01-03',
'2019-01-02'
])->sort()->values()
答案 3 :(得分:0)
好吧,让我们确定问题出在jQuery中(或不是)。尝试使用邮递员(或其他一些HTTP客户端)执行相同的查询。