06.10.2016 Views

laravel-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Collections 313<br />

1 $collection = collect([<br />

2 ['name' => 'Desk', 'price' => 200],<br />

3 ['name' => 'Chair', 'price' => 100],<br />

4 ['name' => 'Bookcase', 'price' => 150],<br />

5 ]);<br />

6<br />

7 $sorted = $collection->sortBy('price');<br />

8<br />

9 $sorted->values()->all();<br />

10<br />

11 /*<br />

12 [<br />

13 ['name' => 'Chair', 'price' => 100],<br />

14 ['name' => 'Bookcase', 'price' => 150],<br />

15 ['name' => 'Desk', 'price' => 200],<br />

16 ]<br />

17 */<br />

The sorted collection keeps the original array keys. In this example we used the values method to<br />

reset the keys to consecutively numbered indexes.<br />

You can also pass your own callback to determine how to sort the collection values:<br />

1 $collection = collect([<br />

2 ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],<br />

3 ['name' => 'Chair', 'colors' => ['Black']],<br />

4 ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],<br />

5 ]);<br />

6<br />

7 $sorted = $collection->sortBy(function ($product, $key) {<br />

8 return count($product['colors']);<br />

9 });<br />

10<br />

11 $sorted->values()->all();<br />

12<br />

13 /*<br />

14 [<br />

15 ['name' => 'Chair', 'colors' => ['Black']],<br />

16 ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],<br />

17 ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!