我有一个集合,可以在array
或object
之间切换,看似随意。会导致这种情况发生的原因是什么?
$events = Event::all();
$events = $events->map(function ($event) use ($request) {
$reducedEventName = Helper::alphaNum($event->name);
$reducedRequestName = Helper::alphaNum($request->name);
$distance = levenshtein($reducedEventName, $reducedRequestName);
return [
'name' => $event->name,
'url' => route('event.view', ['slug' => $event->slug]),
'distance' => $distance,
];
})
->filter(function ($event) {
return $event['distance'] <= Helper::threshold($event['name']);
})
->take(3)
->sortBy('distance');
return $events->toArray();
这个方法是通过XHR调用的,所以我想要原始的JSON
响应。有时它看起来像这个():
[{
"name": "Taylor Swift - Reputation - Release",
"url": "http:\/\/localhost\/e\/lgKejoPSg",
"distance": 22
}, {
"name": "Wiz Khalifa \"Laugh now, fly later\"",
"url": "http:\/\/localhost\/e\/DdLnFD3Qf",
"distance": 24
}]
有时看起来像这样():
{
"1": {
"name": "Wiz Khalifa \"Laugh now, fly later\"",
"url": "http:\/\/localhost\/e\/DdLnFD3Qf",
"distance": 18
},
"0": {
"name": "Taylor Swift - Reputation - Release",
"url": "http:\/\/localhost\/e\/lgKejoPSg",
"distance": 23
}
}
Laravel 5.4
答案 0 :(得分:0)
关于你的问题,我不确定是什么原因导致这种情况发生,因为sortBy()方法声明它返回一个集合。您是否按照刀片返回了确切的$事件?如果是这样,浏览器决定如何处理发送回它的集合可能会出现不一致。您始终可以在查询结尾处使用 - &gt; toArray()以确保它始终返回数组,或者如果您不想对其执行任何其他操作,则可以使用 - &gt; toJson()。
答案 1 :(得分:0)
尝试结果会尝试保留原始密钥,因此我需要丢弃原始密钥:
return array_values($events->toArray());