laravel的Collections方法使用及介绍(翻译二)

这篇博客详细介绍了Laravel Collections的各种实用方法,包括flip、forget、forPage、get、groupBy、has、implode、intersect、intersectByKeys、isEmpty、isNotEmpty、join、keyBy、keys、last、macro、make、map、mapInto、mapSpread和mapToGroups等,帮助读者掌握如何高效操作和处理数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

flip()
flip方法交换collection的key和对应的value的值:

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$flipped = $collection->flip();

$flipped->all();

// ['taylor' => 'name', 'laravel' => 'framework']

forget()
forget方法将会移除key对应的值:

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$collection->forget('name');

$collection->all();

// ['framework' => 'laravel']

forPage()
forPage方法返回一个新的collection,它将包含当前的传入页的数字。这个方法一个参数时接收页的数字,第二个参数数字代表将要展现每一页将要显现的数字:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunk = $collection->forPage(2, 3);

$chunk->all();

// [4, 5, 6]

get()
get方法返回key值对应的元素。假如key不存在时,则会返回null:

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$value = $collection->get('name');

// taylor

你可选第二个参数作为默认值作为:
$collection = collect([‘name’ => ‘taylor’, ‘framework’ => ‘laravel’]);

$value = $collection->get(‘age’, 34);

// 34
你可以调取回调函数作为默认值。假如指定的key不存在时则返回回调函数返回值:

$collection->get('email', function () {
    return 'taylor@example.com';
});

// taylor@example.com

groupBy()
groupBy方法通过传入的key对collection进行分组:

$collection = collect([
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ['account_id' => 'account-x11', 'product' => 'Desk'],
]);

$grouped = $collection->groupBy('account_id');

$grouped->all();

/*
    [
        'account-x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'account-x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

你可以通过回调函数过滤替换key的字符串。这个回调函数会返回键值分组后的值:

$grouped = $collection->groupBy(function ($item, $key) {
    return substr($item['account_id'], -3);
});

$grouped->all();

/*
    [
        'x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

多维分组标准则是通过整个数组。每一个数组元素将会应用于多维数组:

$data = new Collection([
    10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
    20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
    30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
    40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
]);

$result = $data->groupBy(['skill', function ($item) {
    return $item['roles'];
}], $preserveKeys = true);

/*
[
    1 => [
        'Role_1' => [
            10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
            20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
        ],
        'Role_2' => [
            20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
        ],
        'Role_3' => [
            10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
        ],
    ],
    2 => [
        'Role_1' => [
            30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
        ],
        'Role_2' => [
            40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
        ],
    ],
];
*/

has()
has方法用于collection断定key是否存在:

$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);

$collection->has('product');

// true

$collection->has(['product', 'amount']);

// true

$collection->has(['amount', 'price']);

// false

implode()
implode方法用于连接元素。它的判断主要依赖元素的类型。假如collection包含数组或者对象,你应该通过key值进行连接,连接的字符串位于值之间:

$collection = collect([
    ['account_id' => 1, 'product' => 'Desk'],
    ['account_id' => 2, 'product' => 'Chair'],
]);

$collection->implode('product', ', ');

// Desk, Chair

假如collection包含简单的字符串或则数字,你仅仅只要声明连接符号就可以:

collect([1, 2, 3, 4, 5])->implode('-');

// '1-2-3-4-5'

intersect()
intersect方法用于移除源collection中不存在的值。collection将会保留源collection的key值:

$collection = collect(['Desk', 'Sofa', 'Chair']);

$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);

$intersect->all();

// [0 => 'Desk', 2 => 'Chair']

intersectByKeys()
intersectByKeys方法会从原始的collection中去除移除key和它们与之对应的值:

$collection = collect([
    'serial' => 'UX301', 'type' => 'screen', 'year' => 2009,
]);

$intersect = $collection->intersectByKeys([
    'reference' => 'UX404', 'type' => 'tab', 'year' => 2011,
]);

$intersect->all();

// ['type' => 'screen', 'year' => 2009]

isEmpty()

假如collection是空isEmpty方法返回true,反之会返回false:

collect([])->isNotEmpty();

// false

isNotEmpty()
假如collection不为空isNotEmpty方法返回true,反之返回false:

collect([])->isNotEmpty();

// false

join()
join方法将collection的值作为字符串连接起来。用这个方法的第二个参数指定连接时结尾的扩展元素

collect(['a', 'b', 'c'])->join(', '); // 'a, b, c'
collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'
collect(['a', 'b'])->join(', ', ' and '); // 'a and b'
collect(['a'])->join(', ', ' and '); // 'a'
collect([])->join(', ', ' and '); // ''

keyBy()
The keyBy method keys the collection by the given key. If multiple items have the same key, only the last one will appear in the new collection:
keyBy方法通过key返回keys对应的集合。如果多组元素有同样的key,仅只有最后一个将会出现在新的集合中。

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$keyed = $collection->keyBy('product_id');

$keyed->all();

/*
    [
        'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

你也可以调取回调函数。回调返回值和key对应集合。

$keyed = $collection->keyBy(function ($item) {
    return strtoupper($item['product_id']);
});

$keyed->all();

/*
    [
        'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

keys()
keys返回所有collection的键值:

$collection = collect([
    'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
    'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$keys = $collection->keys();

$keys->all();

// ['prod-100', 'prod-200']

last()
last方法返回集合中最后的元素(它经过的函数返回真时):

collect([1, 2, 3, 4])->last(function ($value, $key) {
    return $value < 3;
});

$keys = $collection->keys();

$keys->all();

// 2

你可以调取last方法时不加参数去获取collection中最后的元素。假如集合时空时,将会返回null
collect([1, 2, 3, 4])->last();

// 4

macro()
静态的macro宏方法允许你在运行时给collection类加入方法。涉及到的更多信息的扩展collection文档。

make()
静态make方法创建一个collection实例。查看创建collections的段落。

map()
map方法迭代地通过collection并且通过给定的回调函数调取value的每一个值。回调函数将会方便地更改元素并且会以新的格式返回给新组成的collection。

$collection = collect([1, 2, 3, 4, 5]);

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});

$multiplied->all();

// [2, 4, 6, 8, 10]

mapInto()
mapInto方法通过collection迭代,通过给予的类创建一个新实例并且通过值传入到构造函数中:

class Currency
{
    /**
     * Create a new currency instance.
     *
     * @param  string  $code
     * @return void
     */
    function __construct(string $code)
    {
        $this->code = $code;
    }
}

$collection = collect(['USD', 'EUR', 'GBP']);

$currencies = $collection->mapInto(Currency::class);

$currencies->all();

// [Currency('USD'), Currency('EUR'), Currency('GBP')]

mapSpread()
mapSpread方法迭代地通过collection的每一个元素,调取每一个嵌入的值传入闭包中。闭包函数将会随意的修改原来集合的元素,修改后的元素组成新的集合collection

$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunks = $collection->chunk(2);

$sequence = $chunks->mapSpread(function ($even, $odd) {
    return $even + $odd;
});

$sequence->all();

// [1, 5, 9, 13, 17]

mapToGroups()

mapToGroups方法会按照提供的闭包函数对集合进行分组。闭包函数将会返回按照新的组合值以单一的键和值形式进行关联。
The mapToGroups method groups the collection’s items by the given closure. The closure should return an associative array containing a single key / value pair, thus forming a new collection of grouped values:

$collection = collect([
    [
        'name' => 'John Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Jane Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Johnny Doe',
        'department' => 'Marketing',
    ]
]);

$grouped = $collection->mapToGroups(function ($item, $key) {
    return [$item['department'] => $item['name']];
});

$grouped->all();
/*
    [
        'Sales' => ['John Doe', 'Jane Doe'],
        'Marketing' => ['Johnny Doe'],
    ]
*/

$grouped->get('Sales')->all();
// ['John Doe', 'Jane Doe']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值