Laravel-过滤器收集,然后-> toJson,有一个小问题 [英] Laravel - filter collection and then ->toJson, having a minor issue

查看:251
本文介绍了Laravel-过滤器收集,然后-> toJson,有一个小问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Laravel控制器,它带有一个搜索参数,在特定时间范围内浏览所有记录,使用laravel集合->filter方法,然后在该filter方法的结果上返回json ->json

I have a Laravel controller which takes a search parameter, looks through all the records in a certain time range, uses the laravel collection ->filter method, and then on the results of that filter method, returns the json ->json

$logs = RequestLog::orderBy('created_at', 'DESC')->whereBetween('created_at', [$start, $end])->get();
$logs = $logs->filter(function($log) { /* my own logic in here */ });
return response()->json($logs->toJson());

现在这似乎很好用.它通常返回匹配记录的数组[{"id":1},{"id":2},{"id":3}]

Now this seems to work just fine. It normally returns an array of the matching records, [{"id":1},{"id":2},{"id":3}]

但是,如果->filter函数留下一个结果,比如说数组中的第25条记录,则响应如下所示:{25: {"id": 25}}.它破坏了常规的数组结构,并返回具有单个键的JSON对象.

But if the ->filter function leaves one result, let's say the 25th record in the array, the response now comes out like this: {25: {"id": 25}}. It ruins the normal array structure and returns a JSON object with a single key.

这是预期的吗?这是怎么回事?我该如何处理?

Is this expected? What's up with this? How do I deal with this?

注意:我的filter函数不能通过sql方式完成,必须在PHP中完成.

Note: my filter function cannot be done via sql means, it has to be done in PHP.

[edit]实际上,只要filter结果与原始查询结果中的 first 项不同,它实际上都会返回Object JSON.

[edit] it's actually returning an Object JSON anytime the filter results are anything other than the first items in the original Query results.

推荐答案

通常,在应用修改了集合(尤其是从集合中删除项目)的方法之后,索引可能不会排序.这就是为什么在集合上需要->values()的原因.

Normally after applying methods that modifies (especially removes an item from) a collection, the indexes may not come ordered. This is why you need ->values() on the collection.

因此,您将拥有:

return response()->json($logs->values()->toJson());

values()重置基础阵列上的键.

values() Resets the keys on the underlying array.

这篇关于Laravel-过滤器收集,然后-> toJson,有一个小问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆