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 222<br />

.<br />

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

2<br />

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

4<br />

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

6<br />

7 // [1, 2, 3, 4]<br />

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

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

When dealing with nested arrays or objects, you may specify the key used to determine uniqueness:<br />

.<br />

1 $collection = collect([<br />

2 ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],<br />

3 ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],<br />

4 ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],<br />

5 ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],<br />

6 ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],<br />

7 ]);<br />

8<br />

9 $unique = $collection->unique('brand');<br />

10<br />

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

12<br />

13 /*<br />

14 [<br />

15 ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],<br />

16 ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],<br />

17 ]<br />

18 */<br />

You may also pass your own callback to determine item uniqueness:<br />

.

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

Saved successfully!

Ooh no, something went wrong!