在Yii2中跳过CSV文件的第一行

时间:2018-01-02 09:41:13

标签: csv phpmyadmin yii2 yii-extensions

public function actionUpload(){         $ model = new CsvForm();

    if($model->load(Yii::$app->request->post())){
        $file = UploadedFile::getInstance($model,'file');
        $filename = 'Data.'.$file->extension;
        $upload = $file->saveAs('uploads/'.$filename);
        if($upload){
            define('CSV_PATH','uploads/');
            $csv_file = CSV_PATH . $filename;
            $filecsv = file($csv_file);
            print_r($filecsv);
            foreach($filecsv as $data){

                $modelnew = new Customer1();
                $hasil = explode(",",$data);
                $nim = $hasil[0];
                $nama = $hasil[1];
                $jurusan = $hasil[2];
                $angkatan = $hasil[3];

                $modelnew->username = $nim;
                $modelnew->firstname = $nama;
                $modelnew->lastname = $jurusan;
                $modelnew->password = $angkatan;

                $modelnew->save();
            }
            unlink('uploads/'.$filename);
            return $this->redirect(['site/index']);
        }
    }else{
        return $this->render('upload',['model'=>$model]);
    }
}

这是我的CSV数据

用户1,姓名,通,信息 用户2名,传球,资讯 等。,

所以我想跳过粗体内容并继续执行。

1 个答案:

答案 0 :(得分:0)

您可以移动数组

$filecsvtemp = file($csv_file);
$filecsv = array_shift($filecsvtemp );

以这种方式,数组的第一行不存在于结果数组

否则使用计数器

        $cnt = 0;
        $filecsv = file($csv_file);
        print_r($filecsv);
        foreach($filecsv as $data){

            if ($cnt!=0){
              $modelnew = new Customer1();
              $hasil = explode(",",$data);
              $nim = $hasil[0];
              $nama = $hasil[1];
              $jurusan = $hasil[2];
              $angkatan = $hasil[3];

              $modelnew->username = $nim;
              $modelnew->firstname = $nama;
              $modelnew->lastname = $jurusan;
              $modelnew->password = $angkatan;

              $modelnew->save();

            }
            $cnt++;
        }