Skip to content

Instantly share code, notes, and snippets.

@timwis
Created June 15, 2013 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timwis/5786397 to your computer and use it in GitHub Desktop.
Save timwis/5786397 to your computer and use it in GitHub Desktop.
ATV Election Data Modifier
<?php
ini_set('memory_limit', '-1');
define("FILE_IN", "2012_PRIMARY_SPECIAL.txt");
define("FILE_OUT", "2012_PRIMARY_SPECIAL_mod.csv");
define("FILE_IN_DELIMITER", "\t");
error_reporting(E_ERROR);
if( ($file = fopen(FILE_IN, 'r')) === FALSE ) {
die('Unable to open file ' . FILE_IN);
}
$headers = array();
$data = array();
while(($row = fgetcsv($file, 0, FILE_IN_DELIMITER)) !== FALSE) {
if(empty($headers)) {
$headers = $row;
} else {
$row = array_combine($headers, $row);
$ward = str_pad($row['WARD'], 2, '0', STR_PAD_LEFT);
$division = str_pad($row['DIVISION'], 2, '0', STR_PAD_LEFT);
// Ward
$data[$row['OFFICE']][$ward.'00']['total'] += $row['VOTES'];
$data[$row['OFFICE']][$ward.'00']['candidates'][$row['NAME']] += $row['VOTES'];
// Division
$data[$row['OFFICE']][$ward.$division]['total'] += $row['VOTES'];
$data[$row['OFFICE']][$ward.$division]['candidates'][$row['NAME']] += $row['VOTES'];
}
unset($line);
}
fclose($file);
//echo '<pre>' . print_r($data, true) . '</pre>';
// Build new CSV
if( ($file = fopen(FILE_OUT, 'w')) === FALSE ) {
die('Unable to open file ' . FILE_OUT);
}
// Add headers
$headers = array('WARDDIV'/*, 'WARD', 'DIVISION'*/, 'OFFICE', 'NAME', 'VOTES', 'PERCENTAGE', 'PLURALITY');
fputcsv($file, $headers);
// Add rows
//$rows = array();
foreach($data as $office => $warddivs) {
foreach($warddivs as $warddiv => $details) {
$ward = (int) substr($warddiv, 0, 2);
$division = (int) substr($warddiv, 2);
$winners = array_keys($details['candidates'], max($details['candidates']));
$details['plurality'] = sizeof($winners) == 1 ? $winners[0] : null;
foreach($details['candidates'] as $candidate => $num_votes) {
//$rows []= array(
$row = array(
$warddiv
//,$ward
//,$division
,$office
,preg_replace('/\s+/', ' ', $candidate) // Eliminate multiple spaces (ie. "BARACK OBAMA" becomes "BARACK OBAMA")
,$num_votes
,round($num_votes / $details['total'] * 100, 2)
,$details['plurality'] == $candidate ? 1 : 0
);
fputcsv($file, $row);
}
}
}
fclose($file);
//echo '<pre>' . print_r($rows, true) . '</pre>';
echo 'Finished output to ' . FILE_OUT;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment