首页 > 解决方案 > 验证来自 foreach Laravel 的汇总数组字段

问题描述

目前,我foreach array在收集所有tasks内容并包含weight每个任务的地方工作。

这是我的工作代码

foreach ($arr4 as $row4) {
    $taskCode = strtoupper(str_random(12));
    $insert_data5[] = array(
        'projCode'  =>  $projCode,
        'taskCode'  => $taskCode,
        'taskWeight'  =>  $row4['weight'],
        'plan_days' =>  $row4['planned_days'],
        'actual_days'  =>  $row4['actual_days'],
        'deleted'  =>  0,
        'by_id'  => auth()->user()->id,
        'updated_by'    =>  auth()->user()->name,
        'created_at'    =>  now(),
        'updated_at'    => now(),
        );

}

dd($insert_data5);

输出

在此处输入图像描述

我要做的是验证总和taskWeight是否5 Tasks未达到 100%,这将显示一条错误消息。

截至目前我的想法是使用validator,但我不知道如何计算数组字段taskWeight

  $validator = Validator::make(
                $insert_data5,
                [
                   ......
                ]
            );


   if($validator->fails()){
                return redirect()
                ->back()
                ->with(['errors'=>$validator->errors()->all()])
                ->with('modal',$modal);
            }

标签: phplaravel

解决方案


解决了我的问题

$ttlTaskWeight = 0;在 foreach 之外声明

然后按照建议在里面做总结foreach

像这样

$ttlTaskWeight += $row4['weight'];

我这样做是为了验证它是否超过 100%

    if($ttlTaskWeight != 100){
                return redirect()
                ->back()
                ->with(['errors'=> [0=> 'Total Task Weight must be exact 100%']])
                ->with('modal',$modal);
            }

输出是这个

在此处输入图像描述


推荐阅读