Home  >  Article  >  PHP Framework  >  What are the commonly used collection methods in laravel?

What are the commonly used collection methods in laravel?

青灯夜游
青灯夜游Original
2022-02-23 17:33:054030browse

Commonly used collection methods in laravel include: filter(), search(), chunk(), dump(), map(), zip(), whereNotIn(), max(), pluck(), each( ), tap(), pipe(), contains(), etc.

What are the commonly used collection methods in laravel?

The operating environment of this tutorial: Windows 7 system, Laravel 6 version, Dell G3 computer.

Laravel collection (Collection) common methods

#filter()

filter, the most useful One of the laravel collection methods that allows you to filter the collection using callbacks. It only passes those items that return true. All other items are deleted. filter Returns a new instance without changing the original instance. It accepts value and key as two parameters in the callback.

$filter = $collection->filter(function($value, $key) {
    if ($value['user_id'] == 2) {
        return true;
    }
});

$filter->all();

all Method returns the underlying array. The above code returns the following response.

[
    1 => [
        "user_id" => 2,
        "title" => "Testing in Laravel",
        "content" => "Testing File Uploads in Laravel",
        "category" => "php"
    ]
]

search()

search method searches a collection using a given value. If the value is in the collection, the corresponding key will be returned. If no data item matches the corresponding value, false will be returned.

$names = collect(['Alex', 'John', 'Jason', 'Martyn', 'Hanlin']);

$names->search('Jason');

// 2

search method uses loose comparison by default. You can pass true in its second parameter to use strict comparison.

You can also pass your own callback function to the search method. Will return the key of the first item that passes the callback's truth test.

$names = collect(['Alex', 'John', 'Jason', 'Martyn', 'Hanlin']);

$names->search(function($value, $key) {
    return strlen($value) == 6;
});

// 3

chunk()

chunk method splits a collection into multiple smaller collections of a given size. Very useful for displaying collections into a grid.

$prices = collect([18, 23, 65, 36, 97, 43, 81]);

$prices = $prices->chunk(3);

$prices->toArray();

The above code generates the effect.

[
    0 => [
        0 => 18,
        1 => 23,
        2 => 65
    ],
    1 => [
        3 => 36,
        4 => 97,
        5 => 43
    ],
    2 => [
        6 => 81
    ]
]

dump()

dump Method to print a collection. It can be used for debugging and finding content within a collection at any location.

$collection->whereIn('user_id', [1, 2])
    ->dump()
    ->where('user_id', 1);

dump Results of the above code.

map()

map method is used to traverse the entire collection. It accepts callback as parameter. value and key are passed to the callback. Callbacks can modify values ​​and return them. Finally, a new collection instance of the modified item is returned.

$changed = $collection->map(function ($value, $key) {
    $value['user_id'] += 1;
    return $value;
});

return $changed->all();

Basically, it increases user_id by 1.

The response to the above code is as follows.

[
    [
        "user_id" => 2,
        "title" => "Helpers in Laravel",
        "content" => "Create custom helpers in Laravel",
        "category" => "php"
    ],
    [
        "user_id" => 3,
        "title" => "Testing in Laravel",
        "content" => "Testing File Uploads in Laravel",
        "category" => "php"
    ],
    [
        "user_id" => 4,
        "title" => "Telegram Bot",
        "content" => "Crypto Telegram Bot in Laravel",
        "category" => "php"
    ]
];

zip()

The Zip method merges the values ​​of the given array with the values ​​of the collection. Values ​​with the same index are added together, which means that the first value of the array is merged with the first value of the collection. Here, I'll use the collection we just created above. This also works for Eloquent collections.

$zipped = $collection->zip([1, 2, 3]);

$zipped->all();

The JSON response will look like this.

So, basically that’s it. If the length of the array is less than the length of the collection, Laravel will add null to the end of the remaining elements of type Collection. Similarly, if the length of the array is greater than the length of the collection, Laravel will add null to elements of type Collection, followed by the array value.

whereNotIn()

You can use the whereNotIn method to simply follow the key values ​​that are not contained in the given array Filter the collection. It's basically the opposite of whereIn. Additionally, this method uses relaxed comparison == when matching values.

Let's filter $collection where user_id is neither 1 nor 2.

$collection->whereNotIn('user_id', [1, 2]);

The above statement will only return the last item in $collection. The first parameter is the key and the second parameter is the value array. In the case of eloquent, the first parameter will be the name of the column and the second parameter will be an array of values.

max()

max method returns the maximum value for the given key. You can find the largest user_id by calling max. It's usually used for comparisons like prices or any other number, but for demonstration purposes, let's use user_id. It can also be used with strings, in this case, Z> a.

$collection->max('user_id');

The above statement will return the largest user_id, which in our case is 3.

pluck()

pluck method returns all values ​​for the specified key. It is useful for extracting the values ​​of a column.

$title = $collection->pluck('title');
$title->all();

The result looks like this.

[
  "Helpers in Laravel",
  "Testing in Laravel",
  "Telegram Bot"
]

When using eloquent, you can pass column names as parameters to extract values. pluck Also accepts a second parameter, which can be another column name for a collection of eloquent. It will result in a collection keyed by the value of the second argument.

$title = $collection->pluck('user_id', 'title');
$title->all();

The results are as follows:

[
    "Helpers in Laravel" => 1,
    "Testing in Laravel" => 2,
    "Telegram Bot" => 3
]

each()

each 是一种迭代整个集合的简单方法。 它接受一个带有两个参数的回调:它正在迭代的项和键。 Key 是基于 0 的索引。

$collection->each(function ($item, $key) {
    info($item['user_id']);
});

上面代码,只是记录每个项的 user_id

在迭代 eloquent 集合时,您可以将所有列值作为项属性进行访问。 以下是我们如何迭代所有帖子。

$posts = App\Post::all();

$posts->each(function ($item, $key) {
    // Do something
});

如果回调中返回 false,它将停止迭代项目。

$collection->each(function ($item, $key) {
    // Tasks
    if ($key == 1) {
        return false;
    }
});

tap()

tap() 方法允许你随时加入集合。 它接受回调并传递并将集合传递给它。 您可以对项目执行任何操作,而无需更改集合本身。 因此,您可以在任何时候使用 tap 来加入集合,而不会改变集合。

$collection->whereNotIn('user_id', 3)
    ->tap(function ($collection) {
        $collection = $collection->where('user_id', 1);
        info($collection->values());
    })
    ->all();

在上面使用的 tap 方法中,我们修改了集合,然后记录了值。 您可以对 tap 中的集合做任何您想做的事情。 上面命令的响应是:

[
    [
        "user_id" => "1",
        "title" => "Helpers in Laravel",
        "content" => "Create custom helpers in Laravel",
        "category" => "php"
    ],
    [
        "user_id" => "2",
        "title" => "Testing in Laravel",
        "content" => "Testing File Uploads in Laravel",
        "category" => "php"
    ]
]

你可以看到 tap 不会修改集合实例。

pipe()

pipe 方法非常类似于 tap 方法,因为它们都在集合管道中使用。 pipe 方法将集合传递给回调并返回结果。

$collection->pipe(function($collection) {
    return $collection->min('user_id');
});

上述命令的响应是 1。 如果从 pipe 回调中返回集合实例,也可以链接其他方法。

contains()

contains 方法只检查集合是否包含给定值。 只传递一个参数时才会出现这种情况。

$contains = collect(['country' => 'USA', 'state' => 'NY']);

$contains->contains('USA');
// true

$contains->contains('UK');
// false

如果将 键 / 值 对传递给 contains 方法,它将检查给定的键值对是否存在。

$collection->contains('user_id', '1');
// true

$collection->contains('title', 'Not Found Title');
// false

您还可以将回调作为参数传递给回调方法。 将对集合中的每个项目运行回调,如果其中任何一个项目通过了真值测试,它将返回 true 否则返回 false

$collection->contains(function ($value, $key) {
    return strlen($value['title']) 573da1b87fddfb74414a521675c776db 'usa', 'state' => 'ny']);

$forget->forget('country')->all();

上面代码响应如下:

[
    "state" => "ny"
]

forget 不适用于多维数组。

avg()

avg 方法返回平均值。 你只需传递一个键作为参数,avg 方法返回平均值。 你也可以使用 average 方法,它基本上是 avg 的别名。

$avg = collect([
    ['shoes' => 10],
    ['shoes' => 35],
    ['shoes' => 7],
    ['shoes' => 68],
])->avg('shoes');

上面的代码返回 30 ,这是所有四个数字的平均值。 如果你没有将任何键传递给 avg 方法并且所有项都是数字,它将返回所有数字的平均值。 如果键未作为参数传递且集合包含键 / 值对,则 avg 方法返回 0。

$avg = collect([12, 32, 54, 92, 37]);

$avg->avg();

上面的代码返回 45.4,这是所有五个数字的平均值。

您可以使用这些 laravel 集合方法在您自己的项目中处理集合。

【相关推荐:laravel视频教程

The above is the detailed content of What are the commonly used collection methods in laravel?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn