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

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

The flatten method flattens a multi-dimensional collection into a single dimension:<br />

1 $collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]\<br />

2 );<br />

3<br />

4 $flattened = $collection->flatten();<br />

5<br />

6 $flattened->all();<br />

7<br />

8 // ['taylor', 'php', 'javascript'];<br />

You may optionally pass the function a “depth” argument:<br />

1 $collection = collect([<br />

2 'Apple' => [<br />

3 ['name' => 'iPhone 6S', 'brand' => 'Apple'],<br />

4 ],<br />

5 'Samsung' => [<br />

6 ['name' => 'Galaxy S7', 'brand' => 'Samsung']<br />

7 ],<br />

8 ]);<br />

9<br />

10 $products = $collection->flatten(1);<br />

11<br />

12 $products->values()->all();<br />

13<br />

14 /*<br />

15 [<br />

16 ['name' => 'iPhone 6S', 'brand' => 'Apple'],<br />

17 ['name' => 'Galaxy S7', 'brand' => 'Samsung'],<br />

18 ]<br />

19 */<br />

Here, calling flatten without providing the depth would have also flattened the nested arrays,<br />

resulting in ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']. Providing a depth allows you to<br />

restrict the levels of nested arrays that will be flattened.

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

Saved successfully!

Ooh no, something went wrong!