如何在Laravel中从JSON索引计数 [英] How to index count from json in Laravel
问题描述
我有一个带有Structure的消息表,如下所示:
I have a messages table with Structure as follows:
- id sender_id接收者ID pet_id描述
说明是文本消息.我通过获取发件人是用户或收件人是用户的所有消息,然后按我想要的petId过滤它们,来获取与特定宠物相关的用户的消息.
the description is the text message. I am fetching messages of users related to a specific pet by fetching all messages where the sender is user or receiver is user and then filtering them by petId I want.
function messagesByPet($petId,$userId){
$messages = Message::where('sender_id',$userId)->orWhere('receiver_id',$userId)->orderBy('created_at','asc')->get();
$message = $messages->where('pet_id', $petId);
return $message;
}
上面的函数有效,但是我收到的JSON如下.我不希望其中包含诸如"0","3"之类的索引.如何删除它们?
The above function works but the JSON I receive is as follows. I don't want indexes in it such as "0" "3". How to remove them?
{
"0": {
"id": 197,
"sender_id": "5718",
"receiver_id": "5716",
"pet_id": "5113",
"description": "Hi",
"created_at": "2020-03-16 05:29:41",
"updated_at": "2020-03-16 05:29:41"
},
"3": {
"id": 203,
"sender_id": "5718",
"receiver_id": "5716",
"pet_id": "5113",
"description": "Hi",
"created_at": "2020-03-18 22:06:40",
"updated_at": "2020-03-18 22:06:40"
}
}
推荐答案
在get()
方法之后,您获得了集合.因此,您可以使用 values()方法返回包含键的新集合重置为连续的整数:
After get()
method , you got the collection. So you can use values() method to returns a new collection with the keys reset to consecutive integers:
return $message->values();
这篇关于如何在Laravel中从JSON索引计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!