Search code examples
phplaravel-5fgetcsvmaatwebsite-excel

How to get values from a csv file without expected CSV column headers


A user prepares a CSV file for upload. The only mandatory and expected CSV column headers are title and description.

However, the user can have other personal CSV columns headers of their choice. That is, apart from the two mandatory ones title and description a user can opt to include another say remarks time e.t.c.

I would want to get the extra data in all of these other columns altogether (if they exist) and save as an array in one database field data.

However, I can not think of a way to get the extra field data. See below

if($request->hasFile('import_file')){
    $path = $request->file('import_file')->getRealPath();
    $data = Excel::load($path, function($reader) {})->get();
    if(!empty($data) && $data->count()){
        foreach ($data->toArray() as $key => $value) {
            if(!empty($value)){
                foreach ($value as $v) {        
                    $insert[] = ['title' => $v['title'], 'description' => $v['description'], ['data' => $v['xxxxxxxxxxxx'], ];
                }
            }
        }
        if(!empty($insert)){
            Item::insert($insert);
            return back()->with('success','Insert Record successfully.');
        }
    }
}
return back()->with('error','Please Check your file, Something is wrong there.');

How do I get this extra data that is optional and save it as well?

Anyone?


Solution

  • I think your requirement is to take all the columns from the array, except title and description and merge/jsonify them and store it. If this is what you wanted

    $insert = []; //just to be safe declare $insert here 
    foreach ($data->toArray() as $key => $value) {
      if(!empty($value)){
         foreach ($value as $v) {        
            $insert[] = [
               'title' => $v['title'], 
               'description' => $v['description'], 
               'data' => array_except($v,['title', 'description']),//maybe you want to jsonify or merge data 
            ];
         }
      }
    }
    //DB insertion logic
    

    You can read about the array_except() helper function here