简体   繁体   中英

How to convert object array to nested object by using Laravel Collection

I'm working on data assembling in a Laravel project. The data I could get from sql query is like this

[
  {
    "id": 1,
    "name": "John"
  },
  {
    "id": 2,
    "name": "Ben"
  }
]

I want to convert it to something like this,

{
  "1":{
    "name": "John"
  },
  "2":{
    "name": "Ben"
  }
}

Anyway elegant way to do it?

使用keyBy收集方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM