“This is the first day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

To start! Long time no more article, really hand raw, I deleted to write, write to delete.

After a long struggle, LET’s write Laravel’s Collection.

Because my previous habit has been to query data through DB and then toArray() into an array for processing

During this period of time, I have read Laravel’s documents, reviewed the old and learned the new. Collection is worth having, and I want to embrace collection.

The difference between collection and array array

View the source code

Array in Laravel, source code location Illuminate\Support\ arr.php;

In Laravel, Illuminate\Support\ collection.php;

Collections and arrays

  1. A collection is a reencapsulation of an array in the form of an object.
  2. Provides a lot of method functionality (most of these methods use internal callback functions), much more flexible than array operations;
  3. I understand that collections are the difference between manipulating elements as objects and manipulating elements as arrays: if you manipulate them as objects, you can chain them; If you operate according to the array, there will be many intermediate temporary variables or statements, the code is long, difficult to understand, difficult to maintain over time;

Common commands

Create a collection

collect([1, 2, 3]);
Copy the code

Returns the underlying array represented by the collection:

$collection->all();
Copy the code

Returns the average of all items in the collection:

collect([1, 1, 2, 4])->avg()

$collection->average();
Copy the code

To break a collection into smaller collections of a given size:

You can see how it feels to write go here

collect([1, 2, 3, 4, 5])->chunk(2); The results are: [[1,2], [3,4], [5]]Copy the code

To fold a collection of arrays into a single collection of arrays:

collect([[1], [4, 5]])->collapse(); / / [1, 4, 5]Copy the code

Combine the values of one set as keys and the values of another set into a set

collect(['name', 'age'])->combine(['George', 29]); Illuminate\Support\Collection^ {#32 #items: array:2 ["name" => "George" "age" => 29]}Copy the code

Appends the given array or collection value to the end of the collection

collect(['PHP'])->concat(['Laravel']); // ['PHP', 'Laravel']
Copy the code

Determines whether the collection contains the specified item:

collect(['name' => 'Desk'])->contains('Desk'); // true
collect(['name' => 'Desk'])->contains('name',  'Desk'); // true
Copy the code

Returns the total number of items in this collection:

This is the same thing as an array

$collection->count();
Copy the code

Cross-join specifies the values of an array or collection, returning all possible permutations of the Cartesian product

The use in the collection is as follows:

collect([1, 2])->crossJoin(['a', 'b']); Results: [[1, 'a'],[1, 'b'],[2, 'a'],[2, 'b']Copy the code

Just to extend: What is the Cartesian product?

Cartesian product is, in mathematics, the Cartesian product of two sets X and Y, also called the direct product, expressed as X × Y, where the first object is a member of X and the second object is a member of all possible pairs of Y.

Assuming that set A = {A, b}, set b = {0, 1, 2}, the two sets of cartesian product for {(A, 0), (A, 1), (A, 2), (b, 0), (b, 1), (b, 2)}.

Another way to write dd($collection)

collect(['John Doe', 'Jane Doe'])->dd();
Copy the code

To extend: the use of the dd() function

It is important to note that I am a big fan of using DD () to print results, and the source code for the dd function is as follows

if (! function_exists('dd')) { function dd(... $vars) { foreach ($vars as $v) { VarDumper::dump($v); } exit(1); }}Copy the code

If we want to print results and interrupt program execution, the dd() function is a good choice.

Dump () can be used if we want to print results without interrupting program execution:

collect(['John Doe', 'Jane Doe'])->dump();
Copy the code

Returns a value that is present in the original collection but not in the specified collection

collect([1, 2, 3])->diff([2, 4]); Results: [1, 3]Copy the code

Returns data from a collection that is inconsistent with the specified collection key-value pair

This is very useful

collect(['color' => 'orange', 'remain' => 6])->diffAssoc(['color' => 'yellow', 'remain' => 6, 'used' => 6]); ['color' => 'orange']Copy the code

Returns the key/value pair that exists in the original collection but does not exist in the specified collection

collect(['one' => 10, 'two' => 20])->diffKeys(['two' => 2, 'four' => 4]); ['one' => 10]Copy the code

Iterate over the items in the collection and pass them to the given callback function:

$collection = $collection->each(function ($item, $key) {});
Copy the code

Verifies that each element in the collection passes the specified condition test

collect([1, 2])->every(function ($value, $key) { return $value > 1; }); Results: falseCopy the code

Returns all items in the collection that exclude the specified key:

$collection->except(['xxx', 'yyy']);
Copy the code

Welcome to the interactive

Do you have any useful commands to discuss in the comments section

Hardcore articles recommended

Rethinking performance optimization: reduce DB queries and use member variables properly.

PHP to Go mid 2021 summary

How do I receive an interface error at the first time? No need to test the girl to question whether you are not dead interface.

Git use actual combat: collaborative development of many people, emergency repair online bug Git operation guide.

Performance tuning reflection: Do not manipulate DB in a for loop

Performance tuning reflection: Do not operate on DB advanced versions in for loops

The last

👍🏻 : feel the harvest please point a praise to encourage!

🌟 : Collect articles, easy to look back!

💬 : Comment exchange, mutual progress!