生活随笔
收集整理的這篇文章主要介紹了
二十三、PHP框架Laravel学习笔记——集合的常用方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一.常用方法
all()方法,轉(zhuǎn)換為屬性形式輸出,使用 dd 方法看類型;
$collection = collect([1, 2, 2, 3, 4, 4, 4]);
dd($collection->all());
PS:$collection->dd()方法可以以 dd()模式輸出,還有 dump()模式;
avg()方法返回平均值;
$collection = collect([1, 2, 3, 4]);
return $collection->avg();
$collection = collect([['男'=>1], ['女'=>1], ['男'=>3]]);
return $collection->avg('男');
count()方法返回集合總數(shù);
return $collection->count();
PS:相關(guān)的還有 sum()、min()、max()等統(tǒng)計;
countBy()方法返回數(shù)值出現(xiàn)的次數(shù)或回調(diào)函數(shù)指定值出現(xiàn)的次數(shù);
$collection = collect([1, 2, 2, 3, 4, 4, 4]);
return $collection->countBy();
$collection = collect(['xiaoxin@163.com', 'yihu@163.com', 'xiaoying@qq.com']);
return $collection->countBy(function ($value) { return substr(strrchr($value, '@'), 1);
});
PS:相關(guān)的還有 groupBy()、keyBy()方法;
diff()方法返回集合數(shù)組之間不相同的部分,組合新的集合;
$collection = collect([1, 2, 3, 4, 5]);
return $collection->diff([3, 5]);
PS:其中還有 diffAssoc()、diffKeys()派生方法;
duplicates()返回重復(fù)的值;
$collection = collect([1, 2, 2, 3, 4, 5, 5, 6]);
return $collection->duplicates();
duplicatesStrict()
first()返回成立后的第一個值;
$collection = collect([1, 2, 3, 4]);
return $collection->first(function ($value) { return $value > 2;
});
PS:相關(guān)的還有 every()、except()、only()、firstWhere()、last()等方法;
flatten()將多維數(shù)組轉(zhuǎn)換為一維;
$collection = collect(['name'=>'Mr.Lee', 'details'=>['gender'=>'男', 'age'=>100]]);
return $collection->flatten();
get()通過鍵名找值;
$collection = collect(['name'=>'Mr.Lee', 'gender'=>'男']); return $collection->get('name');
PS:相關(guān)的還有 pluck()等;
has()判斷集合中是否存在指定鍵;
return $collection->has('name');
pop()移出集合中最后一個值;
$collection = collect([1, 2, 3, 4, 5]);
return $collection;
PS:相關(guān)的還有 pull()、push()、put()方法;
slice()返回指定值后續(xù)的集合;
$collection = collect([1, 2, 3, 4, 5]);
return $collection->slice(3);
PS:相關(guān)的還有 splice()等方法;
sort()返回指定值后續(xù)的集合;
$collection = collect([3, 1 , 5, 2, 7]);
return $collection->sort()->values();
//需要配合 values()方法
PS:相關(guān)的有 sortBy()、sortByDesc()、sortKeys()等;
where()系列方法,和數(shù)據(jù)庫條件一樣;
$collection = collect([ ['name'=>'Mr.Lee', 'gender'=>'男'], ['name'=>'Miss.Zhang', 'gender'=>'女'] ]);
return $collection->where('name', 'Mr.Lee');
總結(jié)
以上是生活随笔為你收集整理的二十三、PHP框架Laravel学习笔记——集合的常用方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。