Search code examples
laravellaravel-livewire

How to convert lavavel collection to square bracket collection


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.


Solution

  • 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,...])