Laravel 辅助函数

  • TOC
    {:toc}

新增

array_add($array, $field, $value) 不覆盖|不改变原数组

如果给定的键不在数组中,那么 array_add 函数将会把给定的键/值对添加到数组中:

1
2
3
$array = array_add(['name' => 'Desk'], 'price', 100);

// ['name' => 'Desk', 'price' => 100]

array_prepend($array, $value, $key =null) 可覆盖|不改变原数组

array_prepend 函数将一个项目推到数组的开头:

1
2
3
4
5
$array = ['one', 'two', 'three', 'four'];

$array = array_prepend($array, 'zero');

// ['zero', 'one', 'two', 'three', 'four']

你可以指定用于该值的键:

1
2
3
4
5
$array = ['price' => 100];

$array = array_prepend($array, 'Desk', 'name');

// ['name' => 'Desk', 'price' => 100]

array_set($array, 'first.second', $value) 覆盖|改变原数组|返回当前深度数组

array_set 函数使用「点」符号在深度嵌套的数组中设置一个值:

1
2
3
4
5
$array = ['products' => ['desk' => ['price' => 100]]];

array_set($array, 'products.desk.price', 200);

// ['products' => ['desk' => ['price' => 200]]]

data_fill($target, 'frist.second', $value) 不覆盖|改变原结构|返回target

data_fill 函数使用「点」符号在嵌套数组或对象内设置缺少的值:

1
2
3
4
5
6
7
8
9
$data = ['products' => ['desk' => ['price' => 100]]];

data_fill($data, 'products.desk.price', 200);

// ['products' => ['desk' => ['price' => 100]]]

data_fill($data, 'products.desk.discount', 10);

// ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]

该函数也接受星号「 * 」作为通配符,并相应地填写目标:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$data = [
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2'],
],
];

data_fill($data, 'products.*.price', 200);

/*
[
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2', 'price' => 200],
],
]
*/

data_set($target, 'first.second') 嵌套设置|覆盖|改变原结构|返回$target

data_set 函数使用「点」符号在嵌套数组或对象内设置一个值:

1
2
3
4
5
$data = ['products' => ['desk' => ['price' => 100]]];

data_set($data, 'products.desk.price', 200);

// ['products' => ['desk' => ['price' => 200]]]

这个函数也接受通配符「 * 」,并相应地在目标上设置值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$data = [
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2', 'price' => 150],
],
];

data_set($data, 'products.*.price', 200);

/*
[
'products' => [
['name' => 'Desk 1', 'price' => 200],
['name' => 'Desk 2', 'price' => 200],
],
]
*/

默认情况下,所有现有的值都会被覆盖。如果你只想设置一个不存在值,你可以传递 false 作为第三个参数:

1
2
3
4
5
$data = ['products' => ['desk' => ['price' => 100]]];

data_set($data, 'products.desk.price', 200, false);

// ['products' => ['desk' => ['price' => 100]]]

删除

array_except($array, array $except) 排除键/键值对|不改变原数组|返回新数组

array_except 函数从数组中删除给定的键/值对:

1
2
3
$array = ['name' => 'Desk', 'price' => 100];
$filtered = array_except($array, ['price']);
// ['name' => 'Desk']

array_forget($array, 'first.second') 多维数组中移除键/值对|改变原数组|返回null

array_forget 函数使用「点」符号从深度嵌套数组中移除给定的键/值对:

1
2
3
4
5
$array = ['products' => ['desk' => ['price' => 100]]];

array_forget($array, 'products.desk');

// ['products' => []]

array_pull($array, 'key') 删除数组键值对,返回值,改变数组

array_pull 函数返回并从数组中删除键/值对:

1
2
3
4
5
6
7
$array = ['name' => 'Desk', 'price' => 100];

$name = array_pull($array, 'name');

// $name: Desk

// $array: ['price' => 100]

将默认值作为第三个参数传递给该方法。如果键不存在,则返回该值:

1
$value = array_pull($array, $key, $default);

检索

array_first($array, $callback, $default) 返回第一个

array_first 函数返回数组中第一个通过指定测试的元素:

1
2
3
4
5
6
7
$array = [100, 200, 300];

$first = array_first($array, function ($value, $key) {
return $value >= 150;
});

// 200

将默认值作为第三个参数传递给该方法。如果没有值通过测试,则返回该值:

1
$first = array_first($array, $callback, $default);

array_get($array, 'first.second') 多维数组中获取值

array_get 函数使用「点」符号从深度嵌套的数组中检索值:

1
2
3
4
5
$array = ['products' => ['desk' => ['price' => 100]]];

$price = array_get($array, 'products.desk.price');

// 100

array_get 函数也接受一个默认值,如果没有找到指定的健,则返回该值:

1
2
3
$discount = array_get($array, 'products.desk.discount', 0);

// 0

array_has($array, 'first.second'|$array) 多维数组中判断存在值

array_has 函数使用「点」符号检查数组中是否存在给定的项目或项目组:

1
2
3
4
5
6
7
8
9
$array = ['product' => ['name' => 'Desk', 'price' => 100]];

$contains = array_has($array, 'product.name');

// true

$contains = array_has($array, ['product.price', 'product.discount']);

// false

array_last($array, $callback, $default)最后一个

array_last 函数返回数组中最后一个通过指定测试的元素:

1
2
3
4
5
6
7
$array = [100, 200, 300, 110];

$last = array_last($array, function ($value, $key) {
return $value >= 150;
});

// 300

将默认值作为第三个参数传递给该方法。如果没有值通过测试,则返回该值:

1
$last = array_last($array, $callback, $default);

array_only($array, $fields) 仅返回给定数组中指定的键/值对

array_only 函数仅返回给定数组中指定的键/值对:

1
2
3
4
5
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];

$slice = array_only($array, ['name', 'price']);

// ['name' => 'Desk', 'price' => 100]

array_pluck($array, 'developer.name') 数组中返回检索给定键的值

array_pluck 函数从数组中检索给定键的所有值:

1
2
3
4
5
6
7
8
$array = [
['developer' => ['id' => 1, 'name' => 'Taylor']],
['developer' => ['id' => 2, 'name' => 'Abigail']],
];

$names = array_pluck($array, 'developer.name');

// ['Taylor', 'Abigail']

你也可以指定生成的列表的键:

1
2
3
$names = array_pluck($array, 'developer.name', 'developer.id');

// [1 => 'Taylor', 2 => 'Abigail']

array_random($array, $limit = 1) 返回随机值

array_random 函数从数组中返回一个随机值:

1
2
3
4
5
$array = [1, 2, 3, 4, 5];

$random = array_random($array);

// 4 - (retrieved randomly)

你也可以指定要返回的随机数的数量作为第二个可选参数。一旦你指定了第二个参数,即使数量为 1,这个函数也会返回一个数组:

1
2
3
$items = array_random($array, 2);

// [2, 5] - (retrieved randomly)

data_get($target, 'first.second') 嵌套获取值

data_get 函数使用「点」符号从嵌套数组或对象中检索值:

1
2
3
4
5
$data = ['products' => ['desk' => ['price' => 100]]];

$price = data_get($data, 'products.desk.price');

// 100

data_get 函数还接受默认值作为第三个参数,如果找不到指定的键,将返回该值:

1
2
3
$discount = data_get($data, 'products.desk.discount', 0);

// 0

head($array) 第一个(不过滤)

head 函数返回给定数组中的第一个元素:

1
2
3
4
5
$array = [100, 200, 300];

$first = head($array);

// 100

last($array) 最后一个(不过滤)

last 函数返回给定数组中的最后一个元素:

1
2
3
4
5
$array = [100, 200, 300];

$last = last($array);

// 300

数组间操作

array_collapse(...$arrays) 合并数组

array_collapse 函数将多个单数组合并成一个数组:

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

// [1, 2, 3, 4, 5, 6, 7, 8, 9]

array_divide($array) 分割数组为 键值 两个数组

array_divide 函数返回两个数组,一个包含原始数组的健,另一个包含原始数组的值:

1
2
3
4
5
[$keys, $values] = array_divide(['name' => 'Desk']);

// $keys: ['name']

// $values: ['Desk']

array_dot($array) 平铺多维数组为关联数组,「点」连接

array_dot 函数将多维数组平铺到一维数组中,该数组使用「点」符号表示深度:

1
2
3
4
$array = ['products' => ['desk' => ['price' => 100]]];

$flattened = array_dot($array);
// ['products.desk.price' => 100]

array_flatten($array) 平铺多维数组为索引数组

array_flatten 函数将多维数组平铺为一维数组。

1
2
3
4
5
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];

$flattened = array_flatten($array);

// ['Joe', 'PHP', 'Ruby']

array_sort($array, $callback) 排序

array_sort 函数按照其值排序数组:

1
2
3
4
5
$array = ['Desk', 'Table', 'Chair'];

$sorted = array_sort($array);

// ['Chair', 'Desk', 'Table']

你也可以按给定的闭包返回的结果对数组进行排序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$array = [
['name' => 'Desk'],
['name' => 'Table'],
['name' => 'Chair'],
];

$sorted = array_values(array_sort($array, function ($value) {
return $value['name'];
}));

/*
[
['name' => 'Chair'],
['name' => 'Desk'],
['name' => 'Table'],
]
*/

array_sort_recursive($array, $callback) 递归排序

array_sort_recursive 函数使用 sort 函数递归排序数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
$array = [
['Roman', 'Taylor', 'Li'],
['PHP', 'Ruby', 'JavaScript'],
];

$sorted = array_sort_recursive($array);

/*
[
['Li', 'Roman', 'Taylor'],
['JavaScript', 'PHP', 'Ruby'],
]
*/

array_where($array, $callback) 过滤数组

array_where 函数使用给定的闭包来过滤数组:

1
2
3
4
5
6
7
$array = [100, '200', 300, '400', 500];

$filtered = array_where($array, function ($value, $key) {
return is_string($value);
});

// [1 => 200, 3 => 400]

array_wrap() 创建数组

array_wrap 函数将给定的值包装成一个数组。如果给定的值已经是一个数组,则不会被改变:

1
2
3
4
5
$string = 'Laravel';

$array = array_wrap($string);

// ['Laravel']

如果给定的值是空,则返回一个空数组:

1
2
3
4
5
$nothing = null;

$array = array_wrap($nothing);

// []

laravel + dingo/api + jwt 最佳实践

tymon/jwt-auth

安装

1
composer require tymon/jwt-auth:1.0.0-rc.5

需要注意的是jwtlaravel 5.7以上需要著名安装的版本

生成配置文件

1
php artisan jwt:secret

发布资源

1
2
3
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
# 或者不注明提供者,然后自己输入
php artisan vendor:publish

dingo/api

安装

1
composer requre dingo/api

发布资源

1
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"

修改配置 config\api.php

1
2
3
4
5
6
7
8
9
10
...

'subtype' => env('API_SUBTYPE', 'blog'),
'prefix' => env('API_PREFIX', 'api'),
'auth' => [
'jwt' => 'Dingo\Api\Auth\Provider\JWT',

],
...

修改配置 config\auth.php 将默认

1
2
3
4
5
6
7
8
...

'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
...

laravel集合方法

  • TOC
    {:toc}

all()
all 方法返回该集合表示的底层数组:

1
2
collect([1, 2, 3])->all();
// [1, 2, 3]

average()
avg 方法的别名。

avg()
avg 方法返回给定的 平均值 :

1
2
3
4
5
6
7
$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');

// 20

$average = collect([1, 1, 2, 4])->avg();

// 2

chunk()
chunk 方法将集合拆成多个指定大小的小集合:

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

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

$chunks->toArray();

// [[1, 2, 3, 4], [5, 6, 7]]

这个方法在使用网格系统的 视图 中特别适用,例如 Bootstrap。想像你有一个 Eloquent 模型的集合要在网格中显示:

1
2
3
4
5
6
7
@foreach ($products->chunk(3) as $chunk)
<div class="row">
@foreach ($chunk as $product)
<div class="col-xs-4">{{ $product->name }}</div>
@endforeach
</div>
@endforeach

collapse()
collapse 方法将多个数组的集合合并成一个数组的集合:

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

$collapsed = $collection->collapse();

$collapsed->all();

// [1, 2, 3, 4, 5, 6, 7, 8, 9]

combine()
combine 方法可以将一个集合的值作为「键」,再将另一个数组或者集合的值作为「值」合并成一个集合:

1
2
3
4
5
6
7
$collection = collect(['name', 'age']);

$combined = $collection->combine(['George', 29]);

$combined->all();

// ['name' => 'George', 'age' => 29]

concat()
concat 方法将给定的数组或集合值附加到集合的末尾:

1
2
3
4
5
6
7
$collection = collect(['John Doe']);

$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);

$concatenated->all();

// ['John Doe', 'Jane Doe', 'Johnny Doe']

contains()
contains 方法判断集合是否包含给定的项目:

1
2
3
4
5
6
7
8
9
$collection = collect(['name' => 'Desk', 'price' => 100]);

$collection->contains('Desk');

// true

$collection->contains('New York');

// false

你也可以用 contains 方法匹配一对键 / 值,即判断给定的配对是否存在于集合中:

1
2
3
4
5
6
7
8
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);

$collection->contains('product', 'Bookcase');

// false

最后,你也可以传递一个回调到 contains 方法来执行自己的真实测试:

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

$collection->contains(function ($value, $key) {
return $value > 5;
});

// false

contains 方法在检查项目值时使用「宽松」比较,意味着具有整数值的字符串将被视为等于相同值的整数。 相反 containsStrict 方法则是使用「严格」比较进行过滤。

containsStrict()
此方法和 contains 方法类似,但是它却是使用了「严格」比较来比较所有值。

count()
count 方法返回该集合内的项目总数:

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

$collection->count();

// 4

crossJoin()
crossJoin 方法交叉连接给定数组或集合的值,返回所有可能排列的笛卡尔积:

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

$matrix = $collection->crossJoin([‘a’, ‘b’]);

$matrix->all();

/*
[
[1, ‘a’],
[1, ‘b’],
[2, ‘a’],
[2, ‘b’],
]
*/

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

$matrix = $collection->crossJoin([‘a’, ‘b’], [‘I’, ‘II’]);

$matrix->all();

/*
[
[1, ‘a’, ‘I’],
[1, ‘a’, ‘II’],
[1, ‘b’, ‘I’],
[1, ‘b’, ‘II’],
[2, ‘a’, ‘I’],
[2, ‘a’, ‘II’],
[2, ‘b’, ‘I’],
[2, ‘b’, ‘II’],
]
*/

dd()
dd 方法打印集合的项目并结束脚本执行:

$collection = collect([‘John Doe’, ‘Jane Doe’]);

$collection->dd();

/*
Collection {
#items: array:2 [
0 => “John Doe”
1 => “Jane Doe”
]
}
*/
如果你不想终止脚本执行,请使用用 dump 方法代替。

diff()
diff 方法将集合与其它集合或纯 PHP 数组进行值的比较,然后返回原集合中存在而给定集合中不存在的值:

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

$diff = $collection->diff([2, 4, 6, 8]);

$diff->all();

// [1, 3, 5]

diffAssoc()
diffAssoc 该方法与另外一个集合或基于它的键和值的 PHP 数组进行比较。这个方法会返回原集合不存在于给定集合中的键值对:

$collection = collect([
‘color’ => ‘orange’,
‘type’ => ‘fruit’,
‘remain’ => 6
]);

$diff = $collection->diffAssoc([
‘color’ => ‘yellow’,
‘type’ => ‘fruit’,
‘remain’ => 3,
‘used’ => 6
]);

$diff->all();

// [‘color’ => ‘orange’, ‘remain’ => 6]

diffKeys()
diffKeys 方法与另外一个集合或 PHP 数组的「键」进行比较,然后返回原集合中存在而给定的集合中不存在「键」所对应的键值对:

$collection = collect([
‘one’ => 10,
‘two’ => 20,
‘three’ => 30,
‘four’ => 40,
‘five’ => 50,
]);

$diff = $collection->diffKeys([
‘two’ => 2,
‘four’ => 4,
‘six’ => 6,
‘eight’ => 8,
]);

$diff->all();

// [‘one’ => 10, ‘three’ => 30, ‘five’ => 50]

dump()
dump 方法打印集合的项目:

$collection = collect([‘John Doe’, ‘Jane Doe’]);

$collection->dump();

/*
Collection {
#items: array:2 [
0 => “John Doe”
1 => “Jane Doe”
]
}
*/
如果要在打印集合后终止脚本执行,请使用 dd 方法代替。

each()
each 迭代集合中的内容并将其传递到回调函数中:

$collection->each(function ($item, $key) {
//
});
如果你想要中断对内容的迭代,那就从回调中返回 false:

$collection->each(function ($item, $key) {
if (/* some condition */) {
return false;
}
});

eachSpread()
eachSpread 方法迭代集合的项目,将每个嵌套项目的值传递给回调:

$collection = collect([[‘John Doe’, 35], [‘Jane Doe’, 33]]);

$collection->eachSpread(function ($name, $age) {
//
});
你可以通过在回调中返回 false 来终止迭代。

$collection->eachSpread(function ($name, $age) {
return false;
});

every()
every 方法可用于验证集合中每一个元素都通过给定的真实测试:

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

// false

except()
except 方法返回集合中除了指定键以外的所有项目:

$collection = collect([‘product_id’ => 1, ‘price’ => 100, ‘discount’ => false]);

$filtered = $collection->except([‘price’, ‘discount’]);

$filtered->all();

// [‘product_id’ => 1]
与 except 相反的方法,请查看 only。

filter()
filter 方法使用给定的回调函数过滤集合的内容,只留下那些通过给定真实测试的内容:

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

$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});

$filtered->all();

// [3, 4]
如果没有提供回调函数,集合中所有返回 false 的元素都会被移除:

$collection = collect([1, 2, 3, null, false, ‘’, 0, []]);

$collection->filter()->all();

// [1, 2, 3]
与 filter 相反的方法,可以查看 reject。

first()
first 方法返回集合中通过给定真实测试的第一个元素:

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

// 3
你也可以不传入参数使用 first 方法以获取集合中第一个元素。如果集合是空的,则会返回 null:

collect([1, 2, 3, 4])->first();

// 1

firstWhere()
firstWhere 方法返回集合中具有给定键 / 值对第一个元素:

$collection = collect([
[‘name’ => ‘Regena’, ‘age’ => 12],
[‘name’ => ‘Linda’, ‘age’ => 14],
[‘name’ => ‘Diego’, ‘age’ => 23],
[‘name’ => ‘Linda’, ‘age’ => 84],
]);

$collection->firstWhere(‘name’, ‘Linda’);

// [‘name’ => ‘Linda’, ‘age’ => 14]
调用 firstWhere 方法的时候,你还可以使用运算符。

$collection->firstWhere(‘age’, ‘>=’, 18);

// [‘name’ => ‘Diego’, ‘age’ => 23]

flatMap()
flatMap 方法遍历集合并将其中的每个值传递到给定的回调。可以通过回调修改每个值的内容再返回出来,从而形成一个新的被修改过内容的集合。然后再次被合并为一个数组的集合:

$collection = collect([
[‘name’ => ‘Sally’],
[‘school’ => ‘Arkansas’],
[‘age’ => 28]
]);

$flattened = $collection->flatMap(function ($values) {
return array_map(‘strtoupper’, $values);
});

$flattened->all();

// [‘name’ => ‘SALLY’, ‘school’ => ‘ARKANSAS’, ‘age’ => ‘28’];

flatten()
flatten 方法将多维集合转为一维的:

$collection = collect([‘name’ => ‘taylor’, ‘languages’ => [‘php’, ‘javascript’]]);

$flattened = $collection->flatten();

$flattened->all();

// [‘taylor’, ‘php’, ‘javascript’];
你还可以选择性地传入「深度」参数:

$collection = collect([
‘Apple’ => [
[‘name’ => ‘iPhone 6S’, ‘brand’ => ‘Apple’],
],
‘Samsung’ => [
[‘name’ => ‘Galaxy S7’, ‘brand’ => ‘Samsung’]
],
]);

$products = $collection->flatten(1);

$products->values()->all();

/*
[
[‘name’ => ‘iPhone 6S’, ‘brand’ => ‘Apple’],
[‘name’ => ‘Galaxy S7’, ‘brand’ => ‘Samsung’],
]
*/
在这个例子里,调用 flatten 方法时不传入深度参数的话也会将嵌套数组转成一维的,然后返回 [‘iPhone 6S’, ‘Apple’, ‘Galaxy S7’, ‘Samsung’]。传入深度参数能让你限制设置返回数组的层数。

flip()
flip 方法将集合中的键和对应的数值进行互换:

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

$flipped = $collection->flip();

$flipped->all();

// [‘taylor’ => ‘name’, ‘laravel’ => ‘framework’]

forget()
forget 方法通过给定的键来移除掉集合中对应的内容:

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

$collection->forget(‘name’);

$collection->all();

// [‘framework’ => ‘laravel’]
{note} 与大多数集合的方法不同,forget 不会返回修改过后的新集合;它会直接修改原来的集合。

forPage()
forPage 方法返回给定页码上显示的项目的新集合。这个方法接受页码作为其第一个参数和每页显示的项目数作为其第二个参数。

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

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

$chunk->all();

// [4, 5, 6]

get()
get 方法返回给定键的项目。如果该键不存在,则返回 null:

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

$value = $collection->get(‘name’);

// taylor
你可以选择性地传递默认值作为第二个参数:

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

$value = $collection->get(‘foo’, ‘default-value’);

// default-value
你甚至可以将回调函数当作默认值。如果指定的键不存在,就会返回回调的结果:

$collection->get(‘email’, function () {
return ‘default-value’;
});

// default-value

groupBy()
groupBy 方法根据给定的键对集合内的项目进行分组:

$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->toArray();

/*
[
‘account-x10’ => [
[‘account_id’ => ‘account-x10’, ‘product’ => ‘Chair’],
[‘account_id’ => ‘account-x10’, ‘product’ => ‘Bookcase’],
],
‘account-x11’ => [
[‘account_id’ => ‘account-x11’, ‘product’ => ‘Desk’],
],
]
*/
除了传入一个字符串的「键」,你还可以传入一个回调。该回调应该返回你希望用来分组的键的值。

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

$grouped->toArray();

/*
[
‘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 = collect([‘account_id’ => 1, ‘product’ => ‘Desk’]);

$collection->has(‘product’);

// true

implode()
implode 方法合并集合中的项目。其参数取决于集合中项目的类型。如果集合包含数组或对象,你应该传入你希望连接的属性的键,以及你希望放在值之间用来「拼接」的字符串:

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

$collection->implode(‘product’, ‘, ‘);

// Desk, Chair
如果集合包含简单的字符串或数值,只需要传入「拼接」用的字符串作为该方法的唯一参数即可:

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

// ‘1-2-3-4-5’

intersect()
intersect 方法从原集合中删除不在给定「数组」或集合中的任何值。最终的集合会保留原集合的键:

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

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

$intersect->all();

// [0 => ‘Desk’, 2 => ‘Chair’]

intersectByKeys()
intersectByKeys 方法删除原集合中不存在于给定「数组」或集合中的任何键:

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

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

$intersect->all();

// [‘type’ => ‘screen’, ‘year’ => 2009]

isEmpty()
如果集合是空的,isEmpty 方法返回 true,否则返回 false:

collect([])->isEmpty();

// true

isNotEmpty()
如果集合不是空的, isNotEmpty 方法会返回 true;否则返回 false :

collect([])->isNotEmpty();

// false

keyBy()
keyBy 方法以给定的键作为集合的键。如果多个项目具有相同的键, 则只有最后一个项目回显示在新集合中:

$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’],
]
*/
你也可以传入一个回调方法。回调方法返回的值会作为该集合的键:

$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 = 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;
});

// 2
你也可以不传入参数调用 last 方法来获取集合中最后一个元素。如果集合是空的,则返回 null :

collect([1, 2, 3, 4])->last();

// 4

macro()
静态 macro 允许你在运行时将方法添加到 Collection 类中。有关更多信息,请参阅 扩展集合 的文档。

make()
静态 make 可以创建一个新的集合实例。请参阅 创建集合 部分。

map()
map 方法遍历集合并将每一个值传入给定的回调方法。该回调可以任意修改项目并返回,从而形成新的被修改过项目的集合:

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

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

$multiplied->all();

// [2, 4, 6, 8, 10]
{note} 像其他大多数集合方法一样, map 方法会返回一个新的集合实例;它不会修改它所调用的集合。如果你想改变原集合,请使用 transform 方法。

mapInto()
mapInto() 方法可以迭代集合,通过将值传递给构造函数来创建给定类的新实例:

class Currency
{
/**
* 创建新的货币实例
*
* @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 = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

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

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

$sequence->all();

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

mapToGroups()
mapToGroups 方法通过给定的回调方法对集合的项目进行分组。该回调应该返回一个包含单个键 / 值对的关联数组,从而形成一个新的集合:

$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->toArray();

/*
[
‘Sales’ => [‘John Doe’, ‘Jane Doe’],
‘Marketing’ => [‘Johhny Doe’],
]
*/

$grouped->get(‘Sales’)->all();

// [‘John Doe’, ‘Jane Doe’]

mapWithKeys()
mapWithKeys 方法遍历集合并将每个值传给回调。回调会返回一个包含单个键 / 值对的关联数组:

$collection = collect([
[
‘name’ => ‘John’,
‘department’ => ‘Sales’,
‘email’ => ‘john@example.com
],
[
‘name’ => ‘Jane’,
‘department’ => ‘Marketing’,
‘email’ => ‘jane@example.com
]
]);

$keyed = $collection->mapWithKeys(function ($item) {
return [$item[‘email’] => $item[‘name’]];
});

$keyed->all();

/*
[
john@example.com‘ => ‘John’,
jane@example.com‘ => ‘Jane’,
]
*/

max()
max 方法返回给定键的最大值:

$max = collect([[‘foo’ => 10], [‘foo’ => 20]])->max(‘foo’);

// 20

$max = collect([1, 2, 3, 4, 5])->max();

// 5

median()
median 方法返回给定键的 中值 :

$median = collect([[‘foo’ => 10], [‘foo’ => 10], [‘foo’ => 20], [‘foo’ => 40]])->median(‘foo’);

// 15

$median = collect([1, 1, 2, 4])->median();

// 1.5

merge()
merge 方法将合并给定的数组或集合到原集合。如果给定项目中的字符串键与原集合中的字符串键相匹配,给定的项目值将覆盖原集合中的值:

$collection = collect([‘product_id’ => 1, ‘price’ => 100]);

$merged = $collection->merge([‘price’ => 200, ‘discount’ => false]);

$merged->all();

// [‘product_id’ => 1, ‘price’ => 200, ‘discount’ => false]
如果给定的项目的键是数字,这些值将被追加到集合的末尾:

$collection = collect([‘Desk’, ‘Chair’]);

$merged = $collection->merge([‘Bookcase’, ‘Door’]);

$merged->all();

// [‘Desk’, ‘Chair’, ‘Bookcase’, ‘Door’]

min()
min 方法返回给定键的最小值:

$min = collect([[‘foo’ => 10], [‘foo’ => 20]])->min(‘foo’);

// 10

$min = collect([1, 2, 3, 4, 5])->min();

// 1

mode()
mode 方法返回给定键的 众数 :

$mode = collect([[‘foo’ => 10], [‘foo’ => 10], [‘foo’ => 20], [‘foo’ => 40]])->mode(‘foo’);

// [10]

$mode = collect([1, 1, 2, 4])->mode();

// [1]

nth()
nth 方法创建由每隔 n 个元素组成一个的新集合:

$collection = collect([‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]);

$collection->nth(4);

// [‘a’, ‘e’]
你也可以选择传入一个偏移位置作为第二个参数:

$collection->nth(4, 1);

// [‘b’, ‘f’]

only()
only 方法返回集合中所有给定键的所有项目:

$collection = collect([‘product_id’ => 1, ‘name’ => ‘Desk’, ‘price’ => 100, ‘discount’ => false]);

$filtered = $collection->only([‘product_id’, ‘name’]);

$filtered->all();

// [‘product_id’ => 1, ‘name’ => ‘Desk’]
与 only 相反的方法,请查看 except 方法。

pad()
pad 方法将使用给定的值填充数组,直到数组达到指定的大小。此方法的行为与 array_pad PHP 函数功能类似。

要填充到左侧,您应指定负号。如果给定大小的绝对值小于或等于数组的长度,则不会发生填充:

$collection = collect([‘A’, ‘B’, ‘C’]);

$filtered = $collection->pad(5, 0);

$filtered->all();

// [‘A’, ‘B’, ‘C’, 0, 0]

$filtered = $collection->pad(-5, 0);

$filtered->all();

// [0, 0, ‘A’, ‘B’, ‘C’]

partition()
partition 方法可以和 PHP 中的 list 方法结合使用,用来分开通过指定条件的元素以及那些不通过指定条件的元素:

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

list($underThree, $aboveThree) = $collection->partition(function ($i) {
return $i < 3;
});

$underThree->all();

// [1, 2]

$aboveThree->all();

// [3, 4, 5, 6]

pipe()
pipe 方法将集合传给给定的回调并返回结果:

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

$piped = $collection->pipe(function ($collection) {
return $collection->sum();
});

// 6

pluck()
pluck 方法可以获取集合中给定键对应的所有值:

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

$plucked = $collection->pluck(‘name’);

$plucked->all();

// [‘Desk’, ‘Chair’]
你也可以通过传入第二个参数来指定生成的集合的键:

$plucked = $collection->pluck(‘name’, ‘product_id’);

$plucked->all();

// [‘prod-100’ => ‘Desk’, ‘prod-200’ => ‘Chair’]
如果存在重复的键,则最后一个匹配元素将被插入到弹出的集合中:

$collection = collect([
[‘brand’ => ‘Tesla’, ‘color’ => ‘red’],
[‘brand’ => ‘Pagani’, ‘color’ => ‘white’],
[‘brand’ => ‘Tesla’, ‘color’ => ‘black’],
[‘brand’ => ‘Pagani’, ‘color’ => ‘orange’],
]);

$plucked = $collection->pluck(‘color’, ‘brand’);

$plucked->all();

// [‘Tesla’ => ‘black’, ‘Pagani’ => ‘orange’]

pop()
pop 方法从集合中移除并返回最后一个项:

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

$collection->pop();

// 5

$collection->all();

// [1, 2, 3, 4]

prepend()
prepend 方法将给定的值添加到集合的开头:

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

$collection->prepend(0);

$collection->all();

// [0, 1, 2, 3, 4, 5]
你也可以传递第二个参数来设置新增加项的键:

$collection = collect([‘one’ => 1, ‘two’ => 2]);

$collection->prepend(0, ‘zero’);

$collection->all();

// [‘zero’ => 0, ‘one’ => 1, ‘two’ => 2]

pull()
pull 方法把给定键对应的值从集合中移除并返回:

$collection = collect([‘product_id’ => ‘prod-100’, ‘name’ => ‘Desk’]);

$collection->pull(‘name’);

// ‘Desk’

$collection->all();

// [‘product_id’ => ‘prod-100’]

push()
push 方法把给定值添加到集合的末尾:

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

$collection->push(5);

$collection->all();

// [1, 2, 3, 4, 5]

put()
put 方法在集合内设置给定的键值对:

$collection = collect([‘product_id’ => 1, ‘name’ => ‘Desk’]);

$collection->put(‘price’, 100);

$collection->all();

// [‘product_id’ => 1, ‘name’ => ‘Desk’, ‘price’ => 100]

random()
random 方法从集合中返回一个随机项:

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

$collection->random();

// 4 - (随机检索)
你可以选择性传入一个整数到 random 来指定要获取的随机项的数量。只要你显式传递你希望接收的数量时,则会返回项目的集合:

$random = $collection->random(3);

$random->all();

// [2, 4, 5] - (随机检索)
如果集合的项小于给定的数量, 则该方法将抛出 InvalidArgumentException.

reduce()
reduce 方法将每次迭代的结果传递给下一次迭代直到集合减少为单个值:

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

$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
});

// 6
第一次迭代时 $carry 的数值为 null; 然而, 你也可以通过传入第二个参数到 reduce 来指定它的初始值:

$collection->reduce(function ($carry, $item) {
return $carry + $item;
}, 4);

// 10

reject()
reject 方法使用指定的回调过滤集合。如果回调返回 true 就会把对应的项目从集合中移除:

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

$filtered = $collection->reject(function ($value, $key) {
return $value > 2;
});

$filtered->all();

// [1, 2]
与 reject 相反的方法, 可以查看 filter 方法。

reverse()
reverse 方法用来倒转集合中项目的顺序, 并保留原始的健:

$collection = collect([‘a’, ‘b’, ‘c’, ‘d’, ‘e’]);

$reversed = $collection->reverse();

$reversed->all();

/*
[
4 => ‘e’,
3 => ‘d’,
2 => ‘c’,
1 => ‘b’,
0 => ‘a’,
]
*/

search()
search 方法搜索给定的值并返回它的键。如果找不到,则返回 false 。

$collection = collect([2, 4, 6, 8]);

$collection->search(4);

// 1
搜索使用 「宽松」模式比较完成的,这意味着具有整数值的字符串会被认为等于相同值的整数。要使用 「严格」模式来比较,就传入 true 作为该方法的第二个参数:

$collection->search(‘4’, true);

// false
另外,你可以通过回调来搜索第一个通过真实测试的项目:

$collection->search(function ($item, $key) {
return $item > 5;
});

// 2

shift()
shift 方法移除并返回集合的第一个项目:

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

$collection->shift();

// 1

$collection->all();

// [2, 3, 4, 5]

shuffle()
shuffle 方法随机排序集合中的项目:

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

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] - (随机生成)

slice()
slice 方法返回集合中给定索引开始后面的部分:

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

$slice = $collection->slice(4);

$slice->all();

// [5, 6, 7, 8, 9, 10]
如果你想限制返回内容的大小,就将期望的大小作为第二个参数传递给方法:

$slice = $collection->slice(4, 2);

$slice->all();

// [5, 6]
默认情况下,返回的内容将会保留原始键。假如你不希望保留原始的键,你可以使用 values 方法来重新建立索引。

sort()
sort 方法对集合进行排序。排序后的集合保留着原数组的键,所以在这个例子中我们使用 values 方法来把键重置为连续编号的索引:

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

$sorted = $collection->sort();

$sorted->values()->all();

// [1, 2, 3, 4, 5]
如果你有更高级的排序需求,可以通过自己的算法将回调传递到 sort 。请参阅 PHP 文档的 uasort ,这是集合的 sort 方法在底层所调用的。

{tip} 如果你需要对嵌套数组或对象集合进行排序,参考 sortBy 和 sortByDesc 方法。

sortBy()
sortBy 方法通过给定的键对集合进行排序。排序后的集合保留了原数组键,所以在这个例子中,我们使用 values 方法将键重置为连续编号的索引:

$collection = collect([
[‘name’ => ‘Desk’, ‘price’ => 200],
[‘name’ => ‘Chair’, ‘price’ => 100],
[‘name’ => ‘Bookcase’, ‘price’ => 150],
]);

$sorted = $collection->sortBy(‘price’);

$sorted->values()->all();

/*
[
[‘name’ => ‘Chair’, ‘price’ => 100],
[‘name’ => ‘Bookcase’, ‘price’ => 150],
[‘name’ => ‘Desk’, ‘price’ => 200],
]
*/
你还可以传入自己的回调以决定如何对集合的值进行排序:

$collection = collect([
[‘name’ => ‘Desk’, ‘colors’ => [‘Black’, ‘Mahogany’]],
[‘name’ => ‘Chair’, ‘colors’ => [‘Black’]],
[‘name’ => ‘Bookcase’, ‘colors’ => [‘Red’, ‘Beige’, ‘Brown’]],
]);

$sorted = $collection->sortBy(function ($product, $key) {
return count($product[‘colors’]);
});

$sorted->values()->all();

/*
[
[‘name’ => ‘Chair’, ‘colors’ => [‘Black’]],
[‘name’ => ‘Desk’, ‘colors’ => [‘Black’, ‘Mahogany’]],
[‘name’ => ‘Bookcase’, ‘colors’ => [‘Red’, ‘Beige’, ‘Brown’]],
]
*/

sortByDesc()
这个方法与 sortBy 方法一样,但是会以相反的顺序来对集合进行排序。

sortKeys()
sortKeys 方法通过底层关联数组的键来排序集合:

$collection = collect([
‘id’ => 22345,
‘first’ => ‘John’,
‘last’ => ‘Doe’,
]);

$sorted = $collection->sortKeys();

$sorted->all();

/*
[
‘first’ => ‘John’,
‘id’ => 22345,
‘last’ => ‘Doe’,
]
*/

sortKeysDesc()
这个方法与 sortKeys 方法一样,但是会以相反的顺序来对集合进行排序。

splice()
splice 方法删除并返回从给定值后的内容,原集合也会受到影响:

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

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

$chunk->all();

// [3, 4, 5]

$collection->all();

// [1, 2]
你可以传入第二个参数以限制被删除内容的大小:

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

$chunk = $collection->splice(2, 1);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 4, 5]
另外,你可以传入含有新项目的第三个参数来代替集合中删除的项目:

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

$chunk = $collection->splice(2, 1, [10, 11]);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 10, 11, 4, 5]

split()
split 方法将集合按给定的值拆分:

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

$groups = $collection->split(3);

$groups->toArray();

// [[1, 2], [3, 4], [5]]

sum()
sum 方法返回集合内所有项的总和:

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

// 15
如果集合包含嵌套数组或对象,则应该传入一个键来指定要进行求和的值:

$collection = collect([
[‘name’ => ‘JavaScript: The Good Parts’, ‘pages’ => 176],
[‘name’ => ‘JavaScript: The Definitive Guide’, ‘pages’ => 1096],
]);

$collection->sum(‘pages’);

// 1272
另外,你也可以传入回调来决定要用集合中的哪些值进行求和:

$collection = collect([
[‘name’ => ‘Chair’, ‘colors’ => [‘Black’]],
[‘name’ => ‘Desk’, ‘colors’ => [‘Black’, ‘Mahogany’]],
[‘name’ => ‘Bookcase’, ‘colors’ => [‘Red’, ‘Beige’, ‘Brown’]],
]);

$collection->sum(function ($product) {
return count($product[‘colors’]);
});

// 6

take()
take 方法返回给定数量项的新集合:

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

$chunk = $collection->take(3);

$chunk->all();

// [0, 1, 2]
你可以传递负整数从集合末尾获取指定数量的项:

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

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

$chunk->all();

// [4, 5]

tap()
tap 方法将集合传递给回调,在特定点「tap」集合。此举能让你对集合中的项目执行某些操作,而不影响集合本身:

collect([2, 4, 3, 1, 5])
->sort()
->tap(function ($collection) {
Log::debug(‘Values after sorting’, $collection->values()->toArray());
})
->shift();

// 1

times()
静态 times 方法通过回调在给定次数内创建一个新的集合:

$collection = Collection::times(10, function ($number) {
return $number * 9;
});

$collection->all();

// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
使用这个方法可以与工厂结合使用创建出 Eloquent 模型:

$categories = Collection::times(3, function ($number) {
return factory(Category::class)->create([‘name’ => ‘Category #’.$number]);
});

$categories->all();

/*
[
[‘id’ => 1, ‘name’ => ‘Category #1’],
[‘id’ => 2, ‘name’ => ‘Category #2’],
[‘id’ => 3, ‘name’ => ‘Category #3’],
]
*/

toArray()
toArray 方法将集合转换成 PHP 数组。如果集合的值是 Eloquent 模型,那也会被转换成数组:

$collection = collect([‘name’ => ‘Desk’, ‘price’ => 200]);

$collection->toArray();

/*
[
[‘name’ => ‘Desk’, ‘price’ => 200],
]
*/
{note} toArray 也会将所有集合的嵌套对象转换为数组。如果你想获取原数组,可以用 all 方法。

toJson()
toJson 方法将集合转换成 JSON 字符串:

$collection = collect([‘name’ => ‘Desk’, ‘price’ => 200]);

$collection->toJson();

// ‘{“name”:”Desk”, “price”:200}’

transform()
transform 方法迭代集合并对集合内的每个项目调用给定的回调。而集合的内容也会被回调返回的值取代:

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

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

$collection->all();

// [2, 4, 6, 8, 10]
{note} 与大多数集合的方法不同, transform 会修改集合本身。 如果你想创建新的集合,可以用 map 方法。

union()
union 方法将给定的数组添加到集合中。如果给定的数组中含有与原集合一样的键,则原集合的值不会被改变:

$collection = collect([1 => [‘a’], 2 => [‘b’]]);

$union = $collection->union([3 => [‘c’], 1 => [‘b’]]);

$union->all();

// [1 => [‘a’], 2 => [‘b’], 3 => [‘c’]]

unique()
unique 方法返回集合中所有唯一的项目。返回的集合保留着原数组的键,所以在这个例子中,我们使用 values 方法来把键重置为连续编号的索引:

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

$unique = $collection->unique();

$unique->values()->all();

// [1, 2, 3, 4]
在处理嵌套数组或对象时,你可以指定用来确定唯一性的键:

$collection = collect([
[‘name’ => ‘iPhone 6’, ‘brand’ => ‘Apple’, ‘type’ => ‘phone’],
[‘name’ => ‘iPhone 5’, ‘brand’ => ‘Apple’, ‘type’ => ‘phone’],
[‘name’ => ‘Apple Watch’, ‘brand’ => ‘Apple’, ‘type’ => ‘watch’],
[‘name’ => ‘Galaxy S6’, ‘brand’ => ‘Samsung’, ‘type’ => ‘phone’],
[‘name’ => ‘Galaxy Gear’, ‘brand’ => ‘Samsung’, ‘type’ => ‘watch’],
]);

$unique = $collection->unique(‘brand’);

$unique->values()->all();

/*
[
[‘name’ => ‘iPhone 6’, ‘brand’ => ‘Apple’, ‘type’ => ‘phone’],
[‘name’ => ‘Galaxy S6’, ‘brand’ => ‘Samsung’, ‘type’ => ‘phone’],
]
*/
你还可以通过自己的回调来确定项的唯一性

$unique = $collection->unique(function ($item) {
return $item[‘brand’].$item[‘type’];
});

$unique->values()->all();

/*
[
[‘name’ => ‘iPhone 6’, ‘brand’ => ‘Apple’, ‘type’ => ‘phone’],
[‘name’ => ‘Apple Watch’, ‘brand’ => ‘Apple’, ‘type’ => ‘watch’],
[‘name’ => ‘Galaxy S6’, ‘brand’ => ‘Samsung’, ‘type’ => ‘phone’],
[‘name’ => ‘Galaxy Gear’, ‘brand’ => ‘Samsung’, ‘type’ => ‘watch’],
]
*/
unique 方法在检查项目值时使用「宽松」模式比较,意味着具有整数值的字符串将被视为等于相同值的整数。 你可以使用 uniqueStrict 方法做「严格」模式比较。

uniqueStrict()
这个方法与 unique 方法一样, 但是,所有的值都用 「严格」模式来比较。

unless()
unless 方法当传入的第一个参数不为 true 的时候,将执行给定的回调:

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

$collection->unless(true, function ($collection) {
return $collection->push(4);
});

$collection->unless(false, function ($collection) {
return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 5]
与 unless 相反的方法,可以查看 when 方法。

unlessEmpty()
whenNotEmpty 方法的别名。

unlessNotEmpty()
whenEmpty 方法的别名。

unwrap()
静态 unwrap 方法返回集合内部的可用值:

Collection::unwrap(collect(‘John Doe’));

// [‘John Doe’]

Collection::unwrap([‘John Doe’]);

// [‘John Doe’]

Collection::unwrap(‘John Doe’);

// ‘John Doe’

values()
values 方法返回键被重置为连续编号的新集合:

$collection = collect([
10 => [‘product’ => ‘Desk’, ‘price’ => 200],
11 => [‘product’ => ‘Desk’, ‘price’ => 200]
]);

$values = $collection->values();

$values->all();

/*
[
0 => [‘product’ => ‘Desk’, ‘price’ => 200],
1 => [‘product’ => ‘Desk’, ‘price’ => 200],
]
*/

when()
when 方法当传入的第一个参数为 true 的时候,将执行给定的回调:

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

$collection->when(true, function ($collection) {
return $collection->push(4);
});

$collection->when(false, function ($collection) {
return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 4]
与 when 相反的方法,可以查看 unless 方法。

whenEmpty()
whenEmpty 方法当集合为空的时候,将执行给定的回调:

$collection = collect([‘michael’, ‘tom’]);

$collection->whenEmpty(function ($collection) {
return $collection->push(‘adam’);
});

$collection->all();

// [‘michael’, ‘tom’]

$collection = collect();

$collection->whenEmpty(function ($collection) {
return $collection->push(‘adam’);
});

$collection->all();

// [‘adam’]

$collection = collect([‘michael’, ‘tom’]);

$collection->whenEmpty(function($collection) {
return $collection->push(‘adam’);
}, function($collection) {
return $collection->push(‘taylor’);
});

$collection->all();

// [‘michael’, ‘tom’, ‘taylor’]
与 whenEmpty 相反的方法,可以查看 whenNotEmpty 方法。

whenNotEmpty()
whenNotEmpty 方法当集合不为空的时候,将执行给定的回调:

$collection = collect([‘michael’, ‘tom’]);

$collection->whenNotEmpty(function ($collection) {
return $collection->push(‘adam’);
});

$collection->all();

// [‘michael’, ‘tom’, ‘adam’]

$collection = collect();

$collection->whenNotEmpty(function ($collection) {
return $collection->push(‘adam’);
});

$collection->all();

// []

$collection = collect();

$collection->whenNotEmpty(function($collection) {
return $collection->push(‘adam’);
}, function($collection) {
return $collection->push(‘taylor’);
});

$collection->all();

// [‘taylor’]
与 whenNotEmpty 相反的方法,可以查看 whenEmpty 方法。

where()
where 方法通过给定的键值过滤集合:

$collection = collect([
[‘product’ => ‘Desk’, ‘price’ => 200],
[‘product’ => ‘Chair’, ‘price’ => 100],
[‘product’ => ‘Bookcase’, ‘price’ => 150],
[‘product’ => ‘Door’, ‘price’ => 100],
]);

$filtered = $collection->where(‘price’, 100);

$filtered->all();

/*
[
[‘product’ => ‘Chair’, ‘price’ => 100],
[‘product’ => ‘Door’, ‘price’ => 100],
]
*/
where 方法在检查项值时使用「宽松」模式比较,这意味着具有整数值的字符串会被认为等于相同值的整数。你可以使用 whereStrict 方法进行「严格」模式比较。

whereStrict()
这个方法和 where 方法类似;不相同的是会「严格」的匹配所有值。

whereIn()
whereIn 方法通过给定的键值对数组来过滤集合:

$collection = collect([
[‘product’ => ‘Desk’, ‘price’ => 200],
[‘product’ => ‘Chair’, ‘price’ => 100],
[‘product’ => ‘Bookcase’, ‘price’ => 150],
[‘product’ => ‘Door’, ‘price’ => 100],
]);

$filtered = $collection->whereIn(‘price’, [150, 200]);

$filtered->all();

/*
[
[‘product’ => ‘Bookcase’, ‘price’ => 150],
[‘product’ => ‘Desk’, ‘price’ => 200],
]
*/
whereIn 方法使用「宽松」的规则来检查项目的值,意味着具有整数值的字符串将被视为等于相同值的整数。你可以使用 whereInStrict 方法做 「严格」的比较。

whereInStrict()
这个方法和 whereIn 方法类似;不相同的是会「严格」的匹配所有值。

whereInstanceOf()
whereInstanceOf 方法通过指定类来过滤指定的集合:

$collection = collect([
new User,
new User,
new Post,
]);

return $collection->whereInstanceOf(User::class);

whereNotIn()
whereNotIn 方法通过指定不包含在集合中的键值对数组对数组进行过滤:

$collection = collect([
[‘product’ => ‘Desk’, ‘price’ => 200],
[‘product’ => ‘Chair’, ‘price’ => 100],
[‘product’ => ‘Bookcase’, ‘price’ => 150],
[‘product’ => ‘Door’, ‘price’ => 100],
]);

$filtered = $collection->whereNotIn(‘price’, [150, 200]);

$filtered->all();

/*
[
[‘product’ => ‘Chair’, ‘price’ => 100],
[‘product’ => ‘Door’, ‘price’ => 100],
]
*/
whereNotIn 方法使用「宽松」的规则来检查项目的值,意味着具有整数值的字符串将被视为等于相同值的整数。你可以使用 whereNotInStrict 方法做 「严格」的比较。

whereNotInStrict()
这个方法和 whereNotIn 方法类似;不相同的是会「严格」的匹配所有值。

wrap()
静态调用 wrap 方法将可用的给定值包装在集合中:

$collection = Collection::wrap(‘John Doe’);

$collection->all();

// [‘John Doe’]

$collection = Collection::wrap([‘John Doe’]);

$collection->all();

// [‘John Doe’]

$collection = Collection::wrap(collect(‘John Doe’));

$collection->all();

// [‘John Doe’]

zip()
zip 方法将给定数组的值和相应索引的原集合的值合并在一起:

$collection = collect([‘Chair’, ‘Desk’]);

$zipped = $collection->zip([100, 200]);

$zipped->all();

// [[‘Chair’, 100], [‘Desk’, 200]]

高阶消息传递
集合也提供对 「高阶消息传递」 的支持,即集合常见操作的快捷方式。支持高阶消息传递的集合方法有: average , avg ,contains , each, every , filter ,first , flatMap , groupBy ,keyBy , map ,max , min ,partition , reject ,sortBy , sortByDesc, ,sum , and unique。

每个高阶消息传递都能作为集合实例的动态的属性来访问。 例如,使用 each 高阶消息传递在集合中的每个对象上调用一个方法:

$users = User::where(‘votes’, ‘>’, 500)->get();

$users->each->markAsVip();
同样,我们可以使用 sum 高阶消息传递来收集 users 集合中的「投票」总数 :

$users = User::where(‘group’, ‘Development’)->get();

return $users->sum->votes;

安装pip

原生安装

1
2
$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py   # 下载安装脚本
$ sudo python get-pip.py # 运行安装脚本

epel

pip用来管理python 包很方便。安装pip

(1)首先需要安装epel-release拓展源

首先要明白EPEL的概念
RHEL以及他的衍生发行版如CentOS、Scientific Linux为了稳定,官方的rpm repository提供的rpm包往往是很滞后的,当然了,这样做这是无可厚非的,毕竟这是服务器版本,安全稳定是重点,官方的rpm repository提供的rpm包也不够丰富,很多时候需要自己编译那太辛苦了,而EPEL恰恰可以解决这两方面的问题。
EPEL的全称叫 Extra Packages for Enterprise Linux 。EPEL是由 Fedora 社区打造,为 RHEL 及衍生发行版如 CentOS、Scientific Linux 等提供高质量软件包的项目。装上了 EPEL之后,就相当于添加了一个第三方源。
如果你知道rpmfusion.org的话,拿 rpmfusion 做比较还是很恰当的,rpmfusion 主要为桌面发行版提供大量rpm包,而EPEL则为服务器版本提供大量的rpm包,而且大多数rpm包在官方 repository 中是找不到的。
另外一个特点是绝大多数rpm包要比官方repository 的rpm包版本要来得新.

1
yum -y install epel-release

(2)随后,makecache

1
yum makecache

(3)安装pip 

1
yum -y install python-pip

(4)升级pip

1
2
3
pip install --upgrade pip

pip3 -V

安装 rvm

1
curl -L get.rvm.io | bash -s stable

如果出现一下错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload Upload Total Spent Left Speed
100 194 100 194 0 0 47 0 0:00:04 0:00:04 --:--:-- 47
100 24535 100 24535 0 0 4035 0 0:00:06 0:00:06 --:--:-- 14165
Downloading https://github.com/rvm/rvm/archive/1.29.9.tar.gz
Downloading https://github.com/rvm/rvm/releases/download/1.29.9/1.29.9.tar.gz.asc
gpg: Signature made Wed 10 Jul 2019 04:31:02 PM CST using RSA key ID 39499BDB
gpg: Can't check signature: No public key
GPG signature verification failed for '/usr/local/rvm/archives/rvm-1.29.9.tgz' - 'https://github.com/rvm/rvm/releases/download/1.29.9/1.29.9.tar.gz.asc'! Try to install GPG v2 and then fetch the public key:

gpg2 --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB

or if it fails:

command curl -sSL https://rvm.io/mpapis.asc | gpg2 --import -
command curl -sSL https://rvm.io/pkuczynski.asc | gpg2 --import -

In case of further problems with validation please refer to https://rvm.io/rvm/security

运行,可能需要翻墙

1
gpg2 --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB

再次运行

1
curl -L get.rvm.io | bash -s stable
1
Installing RVM to /usr/local/rvm/

被安装到/usr/local/rvm/,所以rvm真实路径是/usr/local/rvm/bin/rvm

1
/usr/local/rvm/bin/rvm install 2.3.3 

很慢,是国外源需要修改配置

1
2
cd /usr/local/rvm/config/
grep -nR "ruby-lang.org" ./
1
2
./db:78:ruby_url=https://cache.ruby-lang.org/pub/ruby
./db:79:ruby_url_fallback_1=https://ftp.ruby-lang.org/pub/ruby

显示在78行,修改地址为国内源 打开https://github.com/huacnlee/init.d/blob/master/install_rvm其中一句

1
2
3
···
echo "ruby_url=https://cache.ruby-china.com/pub/ruby" > ~/.rvm/user/db
···

将db中的地址改为https://cache.ruby-china.com/pub/ruby

重新安装

1
/usr/local/rvm/bin/rvm install 2.3.3 --disable-binary

yum except KeyboardInterrupt

升级完python后,yum安装发现这个错误;

找了许久才发现是python的问题 

1
2
3
4
5
[root@localhost bin]# yum  
  File "/usr/bin/yum", line 30  
    except KeyboardInterrupt, e:  
                            ^  
SyntaxError: invalid syntax

解决的办法是:

1
vi /usr/bin/yum

将文件头

1
2
3
4
#!/usr/bin/python  
import sys  
try:  
    import yum  

修改为

1
2
3
4
5
#!/usr/bin/python2  
import sys  
try:  
    import yum  
问题解决

明朝皇帝

|庙号|姓名|年号|时间|在位年限|世系|
| – | –|–|–|–|
|明太祖|朱元璋|洪武|1368-1398|30年|朱五四之子|
|明惠宗|朱允炆|建文|1398-1402|4年|朱元璋之孙
朱标次子|
|明成祖|朱棣|永乐|1402-1424|22年|朱元璋四子|
|明仁宗|朱高炽|洪熙|1424-1425|1年|朱棣长子|
|明宣宗|朱瞻基|宣德|1425-1435|10年|朱高炽长子|
|明英宗|朱祁镇|正统
天顺|1435-1449
1457-1464|21|朱瞻基长子|
|明代宗|朱祁钰|景泰|1449-1457|8年|朱瞻基次子|
|明宪宗|朱见深|成化|1464-1487|17年|朱祁镇长子|
|明孝宗|朱佑樘|弘治|1487-1505|18年|朱见深三子|
|明武宗|朱厚照|正德|1505——1521|16年|朱祐樘长子|
|明世宗|朱厚熜|嘉靖|1521——1566|45年|明宪宗之孙
明武宗堂弟|
|明穆宗|朱载坖(ji)|隆庆|1566——1572|6年|朱厚熜第三子|
|明神宗|朱翊钧|万历|1572——1620|48年|朱载坖第三子|
|明光宗|朱常洛|泰昌|1620(29天)|29天|朱翊钧长子|
|明熹宗|朱由校|天启|1620——1627|7年|朱常洛长子|
|明威宗|朱由检|崇祯|1627——1644|14年|朱常洛第五子
朱由校异母弟|

Sequel pro

Sequel-Pro Keyboard Shortcuts Sequel-Pro键盘快捷键


Get the most out of Sequel Pro by remembering the following keyboard shortcuts. 通过记住以下键盘快捷键来最有效地使用Sequel Pro。

Main Tabs 主要标签


Table Structure 表结构

⌘   1

Table Content 表内容

⌘   2

Table Relations 表关系

⌘   3

Table Info 表信息

⌘   4

Custom Query 自定义查询

⌘   5

Table Triggers 表触发器

⌘   6

General Shortcuts 常用快捷键


New Window (Connection File) 新窗口(连接文件)

⌘   N

New Tab(Connection File) 新标签(连接文件)

⌘   T

Add Connection To Favorites 添加连接到收藏夹

⇧   ⌘   A

Open (Connection File or SQL File) 打开(连接文件或者SQL文件)

⌘   O

Open current Connection File in New Window在新窗口打开当前连接

⌥   ⌘   O

Save (Connection File)保存(连接文件)

⌘   S

Save As (Connection File) 另存为(连接文件)

⇧  ⌘   S

Save Query保存查询

^  ⌘   S

Close (Connection File)关闭(连接)

⌘   W

Close All (Connection File) 关闭所有(连接)

⌥   ⌘   W

Print打印

⌘   P

Import 导入

⇧   ⌘   I 

Show Console Window 显示控制台

⇧   ⌘   K

Clear Console 清空控制台

⌘   K 

Back in History 后退

⌃   ⌥   ←

Forward in History 向前

⌃   ⌥   →

Select Next Tab 选择下一个标签

⌃   ⇥

Select Previous Tab 选择上一个标签

⌃   ⇧   ⇥ 

Insert NULL value 插入NULL

⌃   ⇧   N

Copy Create Table Syntax 复制创建表语法

⇧   ⌘   C

Show Create Table Syntax 显示创建表语法

⌥   ⌘   S

Refresh Databases 刷新数据库

⇧   ⌘   R

Choose Database 选择数据库

⇧   ⌘   D

Show Server Variables 显示服务器变量

⇧   ⌘   V

Show Server Processes 显示服务器进程

⌥   ⌘   P

Refresh Tables 刷新数据表

⌃   ⌘   R

Flush Privileges 刷新权限

⇧   ⌘   F

User Accounts… 用户账号

⌘   U

Copy selection / Copy selected row(s) 复制选择/复制选中的行

⌘   C

Copy selected row(s) with column names 复制选中的行包括列名

⌥   ⌘   C

Copy selected row(s) as SQL INSERT 复制选中的行包括插入语句

⌃   ⌥   ⌘   C

Show/Hide Toolbar 显示/隐藏工具栏

⇧   ⌘   T

Filter Table Content 过滤表内容

⌃   ⌘   F

Filter Tables 过滤表

⌃   ⌥   ⌘   F

Bundle Editor 构建编辑器

⌃   ⌥   ⌘   B

Navigator 导航

⌃   ⌥   ⌘   N

Select 选择


Select current word 选择当前单词

⌃   W 

Select current line 选择当前行

⌃   L

Select enclosing brackets 选择括号内

⇧   ⌘   B

Select all 选择所有

⌘   A

Table Structure Tab 表结构标签


Add a new field 新增字段

⌥   ⌘   A

Delete selected field 删除所选字段

Duplicate selected field 选中字段的副本

⌘   D

Refresh table structure 刷新表结构

⌘   R

Edit table details 编辑表详情

⌘   4

Table Content Tab 表内容标签


Add a new row 新增行

⌥   ⌘   A

Delete selected row(s) 删除选中行

Duplicate selected row 选中行的副本

⌘   D

Refresh table contents 刷新表内容

⌘   R

Custom Query Tab 自定义查询标签


Version 1.0 and later 1.0版本以后

Run all queries 运行所有查询

⌥   ⌘   R

Run current query or selection 运行当前或者选中查询

⌅ or ⌘   R

Versions 0.9.9.1 and earlier 1.0版本以前

Run all queries 运行所有查询

⌅ or ⌘   R

Run current query or selection 运行当前或者选中查询

⌥   ⌘   R

Shift line or selection rightwards 左缩进

⌘   [

Shift line or selection leftwards 右缩进

⌘   ]

(Un)Comment line or selection 注释选中行

⌘   /

(Un)Comment current query 注释当前查询

⌥   ⌘   /

Completion (narrow-down list / fuzzy search) 完成(模糊查询)

    Insertion of an item 插入项目

↩ , ⇥ , Double-Click

    Insertion full schema reference

⇧ + ↩ , ⇧   ⇥ , ⇧   Double-Click

    Keep Window Open after Insertion 保存窗口打开后插入

holding down ⌃while insertion

    Fuzzy Search 模糊查询

⌃   ⎋

    Close Window 关闭窗口

Spell Checker Completion (narrow-down list) 拼写检查

F5

Select current query 选择当前查询

⌃   Y

Show MySQL help for current word or selection 显示当前单词或者选择的mysql帮助

⌃   H

Open query favorites popup menu 打开查询收藏夹弹窗

⌥   ⌘   F

Open query history popup menu 打开查询纪录弹窗

⌥   ⌘   Y

Insert previous history item (successively) 插入上一个语句(连续的)

⌃ +  ↑

Insert next history item (successively) 插入下一个语句(连续的)

⌃   ↓

Show all database names as completion list 显示所有数据库名到补齐列表

⌥   ⌘   1

Show all table and view names as completion list 显示所有表名到补齐列表

⌥   ⌘   2

Show all table names from current database as completion list 显示当前数据库的所有表名到补齐列表

⌥   ⌘   3