29.07.2016 Views

laravel-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Collections 216<br />

.<br />

1 $collection = collect([5, 3, 1, 2, 4]);<br />

2<br />

3 $sorted = $collection->sort();<br />

4<br />

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

6<br />

7 // [1, 2, 3, 4, 5]<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 />

For sorting a collection of nested arrays or objects, see the sortBy and sortByDesc methods.<br />

If your sorting needs are more advanced, you may pass a callback to sort with your own algorithm.<br />

Refer to the PHP documentation on usort¹³⁸, which is what the collection’s sort method calls under<br />

the hood.<br />

sortBy() {#collection-method}<br />

The sortBy method sorts the collection by the given key:<br />

.<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 />

¹³⁸http://php.net/manual/en/function.usort.php#refsect1-function.usort-parameters

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

Saved successfully!

Ooh no, something went wrong!