I wrote this to pull one column of data from a csv file, divide each of the results in 2, and then format it as JSON so I can do stuff with it in a web app. It works, but it feels wonky and weird. Is there a better way to do this?
$fname = "subjects.csv";
$half = array();
$otherkeys = array();
$records = array();
if (($handle = fopen($fname, "r")) === FALSE) {
exit;
}
/* First line is header with keys */
$keys = fgetcsv($handle);
echo '['; //added the '['. here to get a propoerly formatted JSON response, not sure why I needed to but I did
while (($data = fgetcsv($handle)) !== FALSE) {
$half[] = ''.$data[0]/2; //added the ''. here to get a propoerly formatted JSON response, not sure why I needed to but I did
$otherkeys[] = $keys[0];
$records = array_combine($otherkeys, $half);
$response = json_encode($records);
echo $response;
}
fclose($handle);
echo ']'; //added the ']'. here to get a properly formatted JSON response, not sure why I needed to but I did
Any thoughts are much appreciated.