为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel excel 验证两列的组合不重复

Laravel excel 验证两列的组合不重复

PHP
富国沪深 2021-10-15 10:38:44
我有一个要求,我需要确保用户上传的 Excel 文件在 2 个特定列中没有重复的行。例子:在下面的代码片段,我想标志了该行1和2包含重复的组合COMPANY_CODE和CLERK_CODE:如果发现这样的重复组合,我想拒绝整个文件被导入并让用户知道问题出在哪里。有什么线索吗?
查看完整描述

1 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

不确定 Maat/Laravel Excel 是否可以轻松解决这个问题。所以,我继续创建关联数组,键是两列的连接,我不想在 Excel 中重复。


然后我使用 foreach 循环手动检查,如果关联数组中存在键,则意味着 Excel 中存在重复条目。


一些示例代码供参考如下:


        $array = Excel::toArray(new MyExcelImport(), request()->file);


        $assoc_array = array();

        foreach ($array[0] as $key => $value) {

            $new_key = $value['company_code'] . $value['clerk_code'];


            // Presence of combination of company_code and clerk_code in the assoc_array indicates that

            // there is duplicate entry in the Excel being imported. So, abort the process and report this to user.

            if (array_key_exists($new_key, $assoc_array)) {

                return response()->json("Combination of company_code: " .

                    $value['company_code'] .

                    " and clerk_code: " .

                    $value['clerk_code'] .

                    " is duplicate in the file being imported. Please correct same and retry upload.", 422);

            }


            $assoc_array[$new_key] = $value;

        }

希望这可以帮助有类似需求的人!


查看完整回答
反对 回复 2021-10-15
  • 1 回答
  • 0 关注
  • 184 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信