【问题标题】:How to get unique data when comparing the data from excel and the data from the database比较excel中的数据和数据库中的数据时如何获取唯一数据
【发布时间】:2019-08-26 11:19:53
【问题描述】:

我正在尝试在 Laravel 中导入一个 excel 表,但问题是如果用户不小心导入了同一个 excel 表,或者如果他导入了另一个与数据库中具有相同数据的 excel 表,那么数据将被重复,我想避免这种情况,所以我想在导入数据之前做一些验证

我尝试从数据库中获取数据和数据表单 excel 并将它们加入一个数组并使用 php 函数 array_unique() 但它显示错误数组到字符串转换

我的路线:

//Uploading Excel Routes
Route::get('/cvs/upload','UploadController@index');
Route::post('/cvs/uploadFile','UploadController@csvfileupload');

我的控制器

public function csvfileupload(Request $request)
    {
        if ($request->input('submit') != null ){
            $file = $request->file('file');
            // File Details
            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $tempPath = $file->getRealPath();
            $fileSize = $file->getSize();
            $mimeType = $file->getMimeType();

            // Valid File Extensions
            $valid_extension = array("csv");

            // 2MB in Bytes
            $maxFileSize = 2097152;

            // Check file extension
            if(in_array(strtolower($extension),$valid_extension)){
                // Check file size
                if($fileSize <= $maxFileSize){
                    // File upload location
                    $location = 'uploads';
                    // Upload file
                    $file->move($location,$filename);
                    // Import CSV to Database
                    $filepath = public_path($location."/".$filename);
                    // Reading file
                    $file = fopen($filepath,"r");
                    $importData_arr = array();
                    $i = 0;

                    while (($filedata = fgetcsv($file, 1300, ",")) !== FALSE) {
                        $num = count($filedata );
                        for ($c = 0; $c < $num; $c++) {
                            $importData_arr[$i][] = $filedata [$c];
                        }
                        $i++;
                    }
                    fclose($file);
                    // Check For Unique Values On Excel Sheet
                    $tempArr = array_unique(array_column($importData_arr, 1));

                    $vals = array_intersect_key($importData_arr, $tempArr);

                    // Get Current Time
                    $mytime = Carbon\Carbon::now();

                    // Insert The values in the Categories Table
                        foreach ($vals as $importData) {
                            $insertData = array("categories_name" => str_slug($importData[1]), "created_at" => $mytime->toDateTimeString());
                            Categories::insert($insertData);
                        }

                    Session::flash('message','Import Successful.');
                }else{
                    Session::flash('message','File too large. File must be less than 2MB.');
                }
            }else{
                Session::flash('message','Invalid File Extension.');
            }
        }
        // Redirect to index
        return redirect()->action('UploadController@index');
    }
}

我的视图文件:

@section('content')
    <!-- Message -->
    @if(Session::has('message'))
        <p >{{ Session::get('message') }}</p>
    @endif
    <center>
        <!-- Form -->
        <form action="/cvs/uploadFile" method="post" class="upload" enctype="multipart/form-data">
            {{ csrf_field() }}
            <input type='file' name='file' >
            <input type='submit' name='submit' value='Import'>
        </form>
    </center>
    <br>
    <br>
@endsection

【问题讨论】:

    标签: php excel laravel import


    【解决方案1】:

    如我所见,您的索引为 1 的列必须是唯一的。

    那么,为什么不用它作为数组的键呢?这意味着不需要函数array_unique

    while (($filedata = fgetcsv($file, 1300, ",")) !== FALSE) {
        $num = count($filedata);
        $row = [];
        for ($c = 0; $c < $num; $c++) {
            $row[] = $filedata[$c];
        }
        // Here we set array with unique column like key
        $importData_arr[$row[1]] = $row;
        $i++;
    }
    

    此代码将被替换为

    $tempArr = array_unique(array_column($importData_arr, 1));
    
    $vals = array_intersect_key($importData_arr, $tempArr);
    

    $vals 你必须使用$importData_arr

    【讨论】:

    • 好的。但是如何获取excel表和数据库之间的唯一数据
    • 当您的数组具有唯一键时,您可以对表执行一个请求并获取所有行,其中包含来自$importData_arr 的键。就像$exists = Categories::where('column', array_keys($importData_arr))-&gt;get(['column'])-&gt;keyBy('column'); 然后,当您插入数组时,添加检查:foreach ($importData_arr as $key =&gt; $importData) { if (array_key_exists($key, $exists)) continue; ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多