Created
December 15, 2014 11:56
-
-
Save mamchenkov/99fb75dafe0547f6317f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Sample data from data.csv | |
//line 1, product 1, feature 1 | |
//line 2, product 1, feature 2 | |
//line 3, product 1, feature 3 | |
//line 4, product 2, feature 1 | |
//line 5, product 3, feature 1 | |
class Product { | |
// Product lines until we save | |
protected $data; | |
public function __construct() { | |
// Make sure $this->data is an array | |
if (empty($this->data)) { | |
$this->data = array(); | |
} | |
} | |
public function process($data) { | |
// First product line ever or | |
// first product line after save | |
if (empty($this->data)) { | |
$this->data[] = $data; | |
return; | |
} | |
// We can compare stuff now | |
$processResult = $this->import($data); | |
// Empty $this->data after saving product to DB | |
if ($processResult) { | |
$this->data = array(); | |
} | |
$this->data[] = $data; | |
} | |
public function import($data) { | |
$result = false; | |
if (!empty($this->data)) { | |
$lastProduct = $this->data[ sizeof($this->data) - 1 ]; | |
if ($lastProduct[1] <> $data[1]) { | |
echo "Saving " . $lastProduct[1] . " to the database\n"; | |
$this->dbInsert(); | |
$result = true; | |
} | |
} | |
return $result; | |
} | |
public function dbInsert() { | |
foreach ($this->data as $item) { | |
print "INSERT INTO PRODUCTS $item[0], $item[1], $item[2]\n"; | |
} | |
} | |
public function __destruct() { | |
if (!empty($this->data)) { | |
$lastItem = $this->data[ sizeof($this->data) - 1 ]; | |
$emptyItem = array(); | |
foreach ($lastItem as $key => $value) { | |
$emptyItem[$key] = null; | |
} | |
$this->process($emptyItem); | |
} | |
} | |
} | |
$fh = fopen('data.csv', 'r'); | |
if (!$fh) { | |
die("Failed to open CSV for reading"); | |
} | |
$product = new Product(); | |
while (($data = fgetcsv($fh)) !== false) { | |
$product->process($data); | |
} | |
fclose($fh); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment