laravel - Laravel:获取项目列表和 SUM
问题描述
很难提出问题!好吧,我从 $request 得到这个对象:
{
"_method": "POST",
"_token": null,
"cliente": "1",
"cota": "853",
"grupo": "07384",
"idERP": "1",
"novoSegmento": "3",
"nrocpfCnpj": "00635344000177",
"natureza_juridica": "206-2 - Sociedade Empresária Limitada",
"porte": "MICRO EMPRESA",
"originalSegmento": "7",
"example_length": "10",
"cota853": "12975",
"cota209": "12110"
}
我必须对 cota*** 的值求和,这很棘手。首先,我使用以下方法在 $result 中搜索了单词“cota”:
if (strpos($request, 'cota') !== false) {
return 'true';
}
从现在开始,我不知道如何继续:1-) 获得多少“cota”?2-) 如何获取每个值以求和?
有任何想法吗?这是最好的方法吗?我希望我说清楚了。
提前致谢!
解决方案
如果您使用表单传递它,您可以更好地创建一个数组,cotas
然后使用 laravel 中强大的集合对它们求和,如下所示:
// in your blade
<input name="cota[]" value="100" />
<input name="cota[]" value="200" />
// in the controller
$total = collect($request->get('cota'))->sum();
或遍历请求值并对 cota 求和:
$total = 0;
foreach ( $request->all() as $key => $value )
{
if (strpos($key, 'cota') !== false) {
$total += $value;
}
// or regex version to exclude the cota
if ( preg_match('/cota[0-9]+/', $key) )
{
$total += $value;
}
}
// here you will have the total sum
推荐阅读
- java - 如何使用定制的 CardView 动态填充 ListView?
- laravel - Laravel Eloquent 按特定格式比较日期
- ruby-on-rails-4 - 轨道控制器上的测试顺序
- exact-online - 获取被阻止的 Exact Online 部门列表
- javascript - 我怎样才能使这个事件滑块工作?
- c++ - C++ 猜数字游戏
- docker - 在 Ubuntu 18.04 上安装 Docker?
- mysql - 使用 VBA 在 Microsoft Dynamcis CRM 2011 或 ASPX 中查询信息
- c++ - 递归模板参数包编程
- python - Flask URL 中的 userinfo 组件