Home > Software engineering >  How to convert lavavel collection to square bracket collection
How to convert lavavel collection to square bracket collection

Time:12-17

I have laravel livewire collection as below.

  [
    {
    "date":"2021.09.01-0:00",
    "open":110.177,
    "close":110.175,
    "low":110.172,
    "high":110.18
    },
    {
    "date":"2021.09.01-0:01",
    "open":110.175,
    "close":110.171,
    "low":110.169,
    "high":110.175
    },
    {
    "date":"2021.09.01-0:02",
    "open":110.171,
    "close":110.173,
    "low":110.17,
    "high":110.176
    }
  ]

I would like to convert them into form of square bracket collection without key name as below .

$data = [
          ['2021.09.01-0:00',110.177,110.175,110.172,110.18],
          ['2021.09.01-0:01',110.175,110.171,110.169,110.175],
          ['2021.09.01-0:02',110.171,110.173,110.17,110.176]
       ];

Any advice or guidance on this would be greatly appreciated, Thanks.

CodePudding user response:

You can use collection map method:

The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it

https://laravel.com/docs/8.x/collections#method-map

$expectData = $collection->map(fn($item) => [$item-> date, $item->open,...])

CodePudding user response:

I am not sure what the original data is but you can map over the collection and pull the values; if Eloquent Models:

$data->map(fn ($v) => array_values($v->toArray()))

Would depend upon how you got that original Collection for how it would end up in this scenario.

If you need to restrict what attributes and the order of them returned you can use only on the model:

fn ($v) => array_values($v->only(['date', ...]))
  • Related