php - 如何在 Laravel 中将产品数组的价格与其数量相加
问题描述
我正在尝试计算多种产品的价格总和及其数量。请求是:
[{"product_id": 14, "quantity": 1}, {"product_id": 18, "quantity": 1}, {"product_id": 15, "quantity": 1}]
我从上面的数组中得到 product_ids [14,18,15] 并用 whereIn 找到总和:
Product::whereIn('id', $product_ids)->sum("prices");
在计算总和时如何考虑数量,我可以通过 foreach 来完成,但还有其他解决方案吗?
解决方案
您的“请求”看起来像 json,所以首先我们必须使用将其转换为对象或数组json_decode
。
$json = '[{"product_id": 14, "quantity": 1}, {"product_id": 18, "quantity": 1}, {"product_id": 15, "quantity": 1}]';
$collection = collect(json_decode($json));
$totalPrice = Product::query()
->select('id', 'price')
->whereIn('id', $collection->pluck('product_id')
->cursor() // we don't really need to load the models in memory.
->reduce(function ($accumulated, $product) use ($collection) { // reduce the collection to a single value
return $accumulated + ( $product->price * $collection->firstWhere('product_id', $product->id)->quantity );
}, 0); // set initial $accumulated is 0
或者使用速记闭包
$totalPrice = Product::query()
->select('id', 'price')
->whereIn('id', $collection->pluck('product_id')
->cursor()
->reduce(fn($a, $p) => $a + ( $p->price * $collection->firstWhere('product_id', $p->id)->quantity ), 0);
推荐阅读
- sql - BigQuery:两个数组的异或元素
- java - 想要从ear文件中提取特定的jar文件并将其存储在特定目录中
- python-3.x - Flask 的 test_client() 没有将自定义 HTTP 标头传递给 Flask 应用程序
- java - Lucene 全文搜索仅适用于与搜索字符串完全匹配的标签
- css - 图像容器中的 Fancybox
- node.js - express.js api 应用程序中的内存泄漏
- r - 将文本中包含的半年格式化为日期
- gitversion - GitVersion Mainline - 每次推送的版本增量
- openvswitch - 为什么在wireshark的“任何”接口上捕获数据包时,每个icmp请求都会转换为vxlan隧道中的四个数据包?
- python - 没有名为 livelossplot 的模块