# collection中sum求和
## 计算下列数组中`order_products`下数组元素`price`的和
开始前,使用 `composer require illuminate/support`,获得collect的相关支持。
```
<?php
// 引入package
require __DIR__ . '/vendor/autoload.php';
$orders = [[
'id' => 1,
'user_id' => 1,
'number' => '13908080808',
'status' => 0,
'fee' => 10,
'discount' => 44,
'order_products'=> [
['order_id'=>1,'product_id'=>1,'param'=>'6寸','price'=>555.00,'product'=>['id'=>1,'name'=>'蛋糕名称','images'=>[]]],
['order_id'=>1,'product_id'=>1,'param'=>'7寸','price'=>333.00,'product'=>['id'=>1,'name'=>'蛋糕名称','images'=>[]]],
],
]];
```
### 使用foreach循环数据
```
$price = 0;
foreach ($orders as $order) {
foreach($order['order_products'] as $ordert_product){
$price += $ordert_product['price'];
}
}
dd($price);
```
> 声明临时变量记录总价格,配合两次循环获得总价并累计。
### 将上面的方式改成collection的[map](/collections/map.md)、[flatten](/collections/flatten.md)和[sum](/collections/sum.md)方式
```
collect($orders)->map(function($order){
return $order['order_products'];
})->flatten(1)->map(function($order){
return $order['price'];
})->sum();
```
### 将上面的求解方式改成collection的[flatMap](/collections/flatMap.md)、[pluck](/collections/pluck.md)和[sum](/collections/sum.md)方式
```
collect($orders)->flatMap(function($order){
return $order['order_products'];
})->pluck('price')->sum();
```
### 将上面的求解方式改成collection的[flatMap](/collections/flatMap.md)和[sum](/collections/sum.md)方式
```
collect($orders)->flatMap(function($order){
return $order['order_products'];
})->sum('price');
```
- 介绍
- Laravel5发送邮件使用Service隔离业务
- 如何使用Repository模式
- 如何使用Service模式
- 如何使用Presenter模式
- Laravel 5.* 执行迁移文件报错:Specified key was too long error
- EloquentORM关联关系
- EloquentORM关联关系之一对一
- EloquentORM关联关系之一对多
- EloquentORM关联关系之远层一对多
- EloquentORM关联关系之多对多
- EloquentORM关联关系之多态关联
- EloquentORM关联关系之多对多多态关联
- Laravel测试
- Laravel中涉及认证跳转地址的修改的地方
- Laravel中Collection的基本使用
- all
- avg
- chuck
- collapse
- combine
- contains
- containsStrict
- count
- diff
- diffAssoc
- diffKeys
- each
- every
- except
- filter
- first
- flatMap
- flatten
- flip
- forget
- forPage
- get
- groupBy
- has
- implode
- intersect
- intersectKey
- isEmpty
- isNotEmpty
- keyBy
- keys
- last
- map
- mapWithKeys
- max
- median
- merge
- min
- mode
- nth
- only
- partition
- pipe
- pluck
- pop
- prepend
- pull
- push
- put
- random
- reduce
- reject
- reverse
- search
- shift
- shuffle
- slice
- sort
- sortBy
- sortByDesc
- splice
- split
- sum
- take
- tap
- times
- toArray
- toJson
- transform
- union
- unique
- uniqueStrict
- values
- when
- where
- whereStrict
- whereIn
- whereInStrict
- whereNotIn
- whereNotInStrict
- zip
- Laravel中Collection的实际使用
- collection中sum求和
- collection格式化计算数据
- collection格式化计算数据计算github事件得分总和
- collection格式化markdown数据列表
- collection格式化计算两个数组的数据
- collection中reduce创建lookup数组
- TODO