Skip to content

Commit bee2093

Browse files
committed
Merge pull request #2 from fabiosato/master
Changes to handle empty fields as NULL values
2 parents e64d008 + 2efb822 commit bee2093

File tree

1 file changed

+26
-17
lines changed

1 file changed

+26
-17
lines changed

src/Flynsarmy/CsvSeeder/CsvSeeder.php

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -94,29 +94,38 @@ private function seedFromCSV($filename, $deliminator = ",")
9494
if ( ($handle = fopen($filename, 'r')) !== FALSE )
9595
{
9696
while ( ($row = fgetcsv($handle, 0, $deliminator)) !== FALSE )
97-
{
97+
{
98+
9899
if ( !$header )
99100
{
100101
$header = $row;
101102
$header[0] = $this->strip_utf8_bom($header[0]);
102103
}
103104
else
104-
{
105-
106-
//Hash hashable field if it exists
107-
$row = array_combine($header, $row);
108-
if(isset($row[$this->hashable])){
109-
$row[$this->hashable] = Hash::make($row[$this->hashable]);
110-
}
111-
$data[] = $row;
112-
113-
// Chunk size reached, insert
114-
if ( ++$row_count == $this->insert_chunk_size )
115-
{
116-
$this->run_insert($data);
117-
$data = array();
118-
$row_count = 0;
119-
}
105+
{
106+
// insert only non-empty fields from the csv file
107+
$i = 0;
108+
$row_values = [];
109+
110+
foreach ($header as $key) {
111+
if (!empty($row[$i])) {
112+
$row_values[$key] = $row[$i];
113+
}
114+
$i++;
115+
}
116+
117+
if(isset($row_values[$this->hashable])){
118+
$row_values[$this->hashable] = Hash::make($row_values[$this->hashable]);
119+
}
120+
121+
$data[$row_count] = $row_values;
122+
123+
// Chunk size reached, insert
124+
if ( ++$row_count == $this->insert_chunk_size )
125+
{
126+
$this->run_insert($data);
127+
$row_count = 0;
128+
}
120129
}
121130
}
122131

0 commit comments

Comments
 (0)