joenpc npcsolution
joenpc npcsolution

Reputation: 767

How to covert Laravel's collection to array object collection?

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.

Upvotes: 0

Views: 64

Answers (1)

Sahil Gupta
Sahil Gupta

Reputation: 597

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
   ]
 ]

Upvotes: 1

Related Questions