user3718908x100
user3718908x100

Reputation: 8509

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.

Upvotes: 56

Views: 218100

Answers (2)

Jonathan
Jonathan

Reputation: 11494

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.

Upvotes: 103

AbdulBasit
AbdulBasit

Reputation: 1409

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',

                ]);

            }

Upvotes: 22

Related Questions