0

I have small laravel collection as below.

[
 {
  id: 1,
   data1: 11,
   data2: 12,
   data3: 13,
   created_at: null,
   updated_at: null
 },
 {
   id: 2,
   data1: 14,
   data2: 15,
   data3: 16,
   created_at: null,
   updated_at: null
 }
]

But I would like to convert to array collection like below.

{
 data: [
   [
     11,
     12,
     13
   ],
   [
     14,
     15,
     16
   ]
 ]
}

Appreciated for advice and so sorry for my English. Thank you very much.

joenpc npcsolution
  • 737
  • 4
  • 11
  • 25

1 Answers1

1

Use toArray() which converts this object into an array.

$data->toArray();

Now the collection converted into an array and looks like:-

[
 [
  id: 1,
   data1: 11,
   data2: 12,
   data3: 13,
   created_at: null,
   updated_at: null
 ],
 [
   id: 2,
   data1: 14,
   data2: 15,
   data3: 16,
   created_at: null,
   updated_at: null
 ]
]

But as per your requirements, you don't want associative index for the array, So use

$data = array_values($data);

Now your keys has been removed and final data is:-

[
   [
     11,
     12,
     13
   ],
   [
     14,
     15,
     16
   ]
 ]
Sahil Gupta
  • 578
  • 5
  • 16