php如何使用高阶函数
1、首先学会数组转集合的方式
(1)使用collect函数
$arr = [1, 2, 3, 4, 5];
$collect = collect($arr);
(2)使用array_map函数
$arr = [1, 2, 3, 4, 5];
$collect = array_map(function($item){
return $item * $item;
}, $arr);
2、集合高阶函数使用教程
假设 $collection = collect(['susan', 'bob', 'jason', 'mali']);
(1)使用过滤函数filter()
$result = $collection->filter(function ($value) {
return $value == 'bob';
});
(2)search 方法可以用给定的值查找集合。如果这个值在集合中,会返回对应的键。如果没有数据项匹配对应的值,会返回 false。
$names->search('mali');
// 返回3
(3)dump(),集合打印
collection->dump();
(4)使用map遍历
$result = $collection->map(function ($value) {
return $value .= '123';
});
(5)使用zip()函数
Zip 方法会将给定数组的值与集合的值合并在一起。相同索引的值会添加在一起,这意味着,数组的第一个值会与集合的第一个值合并。在这里,我会使用我们在上面刚刚创建的集合。这对 Eloquent 集合同样有效。
$result = $collection->zip([1, 2, 3]);
(6)whereNotIn按照给定数组中包含的键值过滤集合
$collection = collect([
['user_id' => 1],
['user_id' => 2],
['user_id' => 3],
]);
$result = $collection->whereNotIn('user_id', [1, 2]);
(7)whereNotIn按照给定数组中未包含的键值过滤集合
$collection = collect([
['user_id' => 1],
['user_id' => 2],
['user_id' => 3],
]);
$result = $collection->whereNotIn('user_id', [1, 2]);
(8)max 方法返回给定键的最大值
$collection = collect([
['user_id' => 1],
['user_id' => 2],
['user_id' => 3],
]);
$result = $collection->max('user_id');
//结果为3
(9)pluck 方法返回指定键的所有值。 它对于提取一列的值很有用。
$collection = collect([
['user_id' => 1],
['user_id' => 2],
['user_id' => 3],
]);
$result = $collection->pluck('user_id');
(10)
(11)
(12)
(13)
(14)
(15)