Collection of laravel

Time:2021-6-16

Laravel’s collection class actually has many very practical methods, which are very useful for us to optimize loops. Our goal is to:No more writingforeachCycle!

1、 Sum price sum

     We’ll learnflatMap map sumAnd so on

Collection of laravel

Collection of laravel

Collection of laravel

collect($arr)->pluck('order_products.*.price')->flatten(1)->sum();

2、 Format gate

     Hope to deepenmapUnderstanding and understanding ofmapApplication scenarios of
Collection of laravel
Collection of laravel

3、 Calculate GitHub activity

     After getting the data through the API, it is a mechanism to convert the data into scores. First of all, it will tryforeachAnd then use the collection of laravel to optimize and reconstruct

https://api.github.com/users/…

Collection of laravel

The conventional solution is as follows
Collection of laravel

Collection Refactoring:
Collection of laravel

4、 Transform comment format

    Laravel CollectionInimplodeMethods are actually very useful in some scenariosmap, we can customize the format of each element with a high degree of freedom. This section of video is a common formatMarkdownformat

Collection of laravel

5、 Calculate monthly turnover

     In the previous examples, we all optimized and reconstructed an array. Learn how to use it in this sectionzipMethod to solve the problem of two arrays.

Collection of laravel

Collection of laravel

Collection of laravel

Collection of laravel

6、 Reduce create lookup array

     There is also a very common method in laravel collection:reduceThis is very useful for us to create a lookup array. In this way, we can use collection to reconstruct a complex array and turn it into a simple lookup array like key value.

Collection of laravel

Or:

collect($employees)->pluck('email','name')

7、 Calculate order summary

     When dealing with order problems, you will encounter a variety of summary problems, such as daily sales summary, daily supplier summary, etcsumMethods of black technology and somegroupByCommon application scenarios of

Collection of laravel

Collection of laravel

Collection of laravel

Reference tutorial:Refactoring code with collection
Reference documents:Collection of laravel