如何在导入数据库时用零替换csv文件中的所有空白单元格?
例如:
这个
title;id;rating
cream,20,,
lotion,21,3.5
更改为:
title;id;rating
cream,20,0,
lotion,21,3.5
这是我的功能
public function importProducts(){
$path = $this->fileLocator->locate('@MyBundle/Resources/products.csv');
$file = new \SplFileObject($path);
$reader = new CsvReader($file, ',');
$reader->setHeaderRowNumber(0);
// Create the workflow from the reader
$workflow = new StepAggregator($reader);
// Create a writer: you need Doctrine’s EntityManager.
$doctrineWriter = new DoctrineWriter($this->em, 'AppBundle:Product');
$workflow->addWriter($doctrineWriter);
// Process the workflow
$workflow->process();
}
答案 0 :(得分:3)
您可以添加a converter以返回0而不是空值:
public function importProducts(){
$path = $this->fileLocator->locate('@MyBundle/Resources/products.csv');
$file = new \SplFileObject($path);
$reader = new CsvReader($file, ',');
$reader->setHeaderRowNumber(0);
// Create the workflow from the reader
$workflow = new StepAggregator($reader);
// Create a writer: you need Doctrine’s EntityManager.
$doctrineWriter = new DoctrineWriter($this->em, 'AppBundle:Product');
$workflow->addWriter($doctrineWriter);
//Converter for null values
$converter = new CallbackValueConverter(function ($input) {
if(null === $input) $input = 0;
return $input;
});
//Adding the converter for the desired columns
$workflow->addValueConverter('title', $converter);
$workflow->addValueConverter('id', $converter);
$workflow->addValueConverter('rating', $converter);
// Process the workflow
$workflow->process();
}