首页 > 解决方案 > 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-) 如何获取每个值以求和?

有任何想法吗?这是最好的方法吗?我希望我说清楚了。

提前致谢!

标签: laravelsumstrpos

解决方案


如果您使用表单传递它,您可以更好地创建一个数组,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

推荐阅读