本文介绍了如何从 Laravel 中的 json 索引计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构如下的消息表:

I have a messages table with Structure as follows:

  • id sender_id receiver_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 索引计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 09:51