Skip to content

Instantly share code, notes, and snippets.

@kalmas
Created January 2, 2014 15:42
Show Gist options
  • Save kalmas/8221081 to your computer and use it in GitHub Desktop.
Save kalmas/8221081 to your computer and use it in GitHub Desktop.
read through a 2 column csv. if a the first column value matches a key in the replacements dictionary, replace column 2 with the key value. just some boring throw away code that I feel like I'm always rewriting.
public function rewrite(){
$replacements = <<<EOD
{
"apple" : "fruit",
"tomato" : "fruit",
"kale" : "vegetable"
}
EOD;
$replacements = json_decode($replacements, true);
$in = @fopen(dirname(__FILE__) . '/food-in.csv', 'r');
$out = @fopen(dirname(__FILE__) . '/food-out.csv', 'w');
while (!feof($in))
{
$line = fgets($in);
$parts = explode(',', $line);
if(array_key_exists($parts[0], $replacements)){
fputs($out, $parts[0] . ',' . $replacements[$parts[0]] . "\n");
} else {
fputs($out, $line);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment