M
M
Mazino2019-03-26 15:28:57
Laravel
Mazino, 2019-03-26 15:28:57

How to serialize object properties into a multidimensional structure?

I use the Laravel framework, so when I make a request to the database, I get the following structure as a result:

Collection {#288 ▼
  #items: array:7 [▼
    0 => {#323 ▼
      +"record_id": 1
      +"city_id": 4
      +"value": "90"
      +"from_date": "2017-11-01 00:00:00"
      +"to_date": "2018-11-30 23:59:59"
    }
    1 => {#321 ▼
      +"record_id": 2
      +"city_id": 4
      +"value": "70"
      +"from_date": "2018-12-01 00:00:00"
      +"to_date": "2019-03-31 23:59:59"
    }
    2 => {#324 ▶}
    3 => {#326 ▶}
    4 => {#327 ▶}
    5 => {#328 ▶}
    6 => {#329 ▶}
  ]
}

How to bring it using Eloqunet or native php to
mind
Collection {#288 
  #items: array:3 [
   + city_id(4) => {
      + value(90) => {
         +"from_date": "2017-11-01 00:00:00"
         +"to_date": "2018-11-30 23:59:59"
       }
       + value(70) => {
         +"from_date": "2018-12-01 00:00:00"
         +"to_date": "2019-11-30 23:59:59"
       }
    }
    + city_id(3) => {
    //etc
    }
}


There are many methods in the Eloquenet documentation that allow you to get a similar result, but perhaps due to the lack of a complete understanding of how to achieve the result, it does not work for me. So far the best I have
came out:
Collection {#345 ▼
  #items: array:3 [▼
    4 => Collection {#338 ▼
      #items: array:3 [▼
        90 => Collection {#335 ▼
          #items: array:1 [▼
            0 => {#323 ▼
              +"value": "90"
              +"from_date": "2017-11-01 00:00:00"
              +"to_date": "2018-11-30 23:59:59"
            }
          ]
        }
        70 => Collection {#336 ▶}
        60 => Collection {#337 ▶}
      ]
    }
    3 => Collection {#341 ▼
      #items: array:2 [▼
        90 => Collection {#339 ▼
          #items: array:1 [▼
            0 => {#326 ▼
              +"value": "90"
              +"from_date": "2017-11-01 00:00:00"
              +"to_date": "2019-02-28 23:59:59"
            }
          ]
        }
        60 => Collection {#340 ▶}
      ]
    }
    10 => Collection {#344 ▶}
  ]
}

Almost, but because of the intermediate array at the end, calling the desired property will look like city_id->value[0]->property, which is not very good, because then the data will need to be packed into json and then it will work on the client side. How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Wells, 2019-03-26
@Alex_Wells

->groupBy('city_id')
edit:->groupBy('city_id')->map->groupBy('value')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question