Laravel:获取项目列表和SUM
Laravel: Get a list of items and 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
您可以将请求转换为一个集合并使用如下回调进行求和:
$sum = collect($request->all())->filter(function ($value, $key) {
return Str::startsWith($key, 'cota');
})->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
您可以将请求转换为一个集合并使用如下回调进行求和:
$sum = collect($request->all())->filter(function ($value, $key) {
return Str::startsWith($key, 'cota');
})->sum();