Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array To Collection in Laravel

I have the following array in PHP:

[   {      "website": "example",      "url": "example.com"   },   {      "website": "example",      "url": "example.com"   } ] 

Now I would like to convert this to a collection so I sort by the keys website or url. However when I do this:

$myArray = collect(websites); 

I get this instead:

 {       "0": {          "website": "example",          "url": "example.com"       },       "1": {          "website": "example",          "url": "example.com"       }     } 

And the sorting does not work, I would like to know what I am doing wrong and how I can fix it so I have an array collection of objects I can easily sort.

Edit: I expect the output to be the same as this:

[   {      "website": "example",      "url": "example.com"   },   {      "website": "example",      "url": "example.com"   } ] 

By "sorting does not work" I meant the items are not sorted.

like image 408
user3718908x100 Avatar asked Mar 03 '18 11:03

user3718908x100


2 Answers

Edit; I understand this question is getting a lot of hits based on the title so the TLDR for those people is to use the collect() helper to create a Collection instance. In answer to the questioner's brief:

If you have

$collection = collect([     (object) [         'website' => 'twitter',         'url' => 'twitter.com'     ],     (object) [         'website' => 'google',         'url' => 'google.com'     ] ]); 

You then have your array wrapped in an instance of the Collection class. That means it does not behave like a typical array (- it will be array-like, but don't treat it like it is one -) until you call all() or toArray() on it. To remove any added indices you need to use values().

$sorted = $collection->sortBy('website');  $sorted->values()->all(); 

The expected output:

[      {#769        +"website": "google",        +"url": "google.com",      },      {#762        +"website": "twitter",        +"url": "twitter.com",      }, ] 

See the docs https://laravel.com/docs/5.1/collections#available-methods

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays.

The all method returns the underlying array represented by the collection.

like image 178
Jonathan Avatar answered Sep 18 '22 21:09

Jonathan


In my case I was making an collection to fake a service for test purpose so I use

$collection = new Collection();     foreach($items as $item){                 $collection->push((object)['prod_id' => '99',                                            'desc'=>'xyz',                                            'price'=>'99',                                            'discount'=>'7.35',                  ]);              } 
like image 28
AbdulBasit Avatar answered Sep 21 '22 21:09

AbdulBasit