handleData($array); } public function setCrt($crt_id){ $this->crt_id = $crt_id; } public function getMsg(){ return $this->msg; } public function setMsg($msg){ $this->msg = $msg; } public function handleData (array $array) { // 去除表头 unset($array[0]); if(empty($array)) { $this->setMsg('数据不能为空!'); return ; } //第一次表格数据校验 非空 已经过滤数据 foreach ($array as $key => $value){ if(empty($value[0]) && empty($value[1]) && empty($value[2]) && empty($value[3])) { unset($array[$key]); }elseif(empty($value[0]) || empty($value[1]) || empty($value[2]) || empty($value[3])) { $this->setMsg('数据必须完整填写!'); return ; }else{ if(! is_numeric($value[3])){ $this->setMsg('请输入正确的金额!'); return ; } } } if(empty($array)) { $this->setMsg('数据不能为空!'); return ; } $array = array_values($array); //默认拆分金额 $setting = Settings::where('name','defaultAmount')->first(); if(empty($setting) || ! is_numeric($setting->value) || $setting->value <= 0) { $this->setMsg('请确认默认拆分金额是否正确!'); return ; } $defaultAmount = (float)$setting->value; //生成时间 $crt_time = time(); //出账主表和子表数据 $main = $sub = []; foreach ($array as $key => $value){ //主表数据 $main[] = [ 'finance_account_name' => $value[0], 'account' => $value[1], 'ifsc' => $value[2], 'amount' => $value[3], 'crt_id' => $this->crt_id, 'crt_time' => $crt_time ]; $totalAmount = (float)$value[3]; $num = floor($totalAmount / $defaultAmount); // 拆分出来的次数 if((int)$num <= 1){ $sub[$key][] = [ 'amount' => $totalAmount ]; }else{ $remainingAmount = $totalAmount % $defaultAmount; // 剩余的金额 $equalAmount = floor($totalAmount / $num); // 平均金额 $lastAmount = $equalAmount + $remainingAmount; // 最后金额(加上剩余的金额) for ($i = 0;$i < (int)$num; $i++){ if ($i == (int)$num - 1) { // 最后一次 $tmp = $lastAmount; } else { $tmp = $equalAmount; } $sub[$key][] = [ 'amount' => $tmp ]; } } } try{ DB::beginTransaction(); Finance::insert($main); //获取上一次插入的所有id $last_insert_id = Finance::where('crt_time',$crt_time)->select('id')->get()->toArray(); $last_insert_id = array_column($last_insert_id,'id'); $insert_sub = []; foreach ($sub as $key => $value){ foreach ($value as $v){ $insert_sub[] = [ 'amount' => $v['amount'], 'finance_id' => $last_insert_id[$key], 'crt_time' => $crt_time ]; } }unset($main);unset($sub); FinanceDetail::insert($insert_sub); DB::commit(); }catch (\Exception $e){ DB::rollBack(); $this->setMsg($e->getMessage()); } } }