Laravel:获取项目列表和总和

时间:2019-07-02 13:58:41

标签: laravel sum strpos

很难提问题! 好吧,我有$ 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-)如何获得每个值的总和?

有什么想法吗?这是最好的方法吗? 我希望我能说清楚。

谢谢!

2 个答案:

答案 0 :(得分:3)

如果使用表单传递此参数,则最好制作一个cotas数组,然后使用laravel中强大的集合对其求和,如下所示:

// in your blade

<input name="cota[]" value="100" />
<input name="cota[]" value="200" />

// in the controller

$total = collect($request->get('cota'))->sum();

或遍历请求值并求和:

$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

答案 1 :(得分:0)

您可以将请求转换为集合,并使用如下所示的回调进行总和:

$sum = collect($request->all())->filter(function ($value, $key) {
    return Str::startsWith($key, 'cota');
})->sum();

相关问题