The .csv file:
question1,question2,question3,question4,question5,question6,question7,question8,question9,question10
yes,response,response,response,response,response,response,response,response,response
yes,response2,response2,response2,response2,response2,response2,response2,response2,response2
no,response3,response3,response3,response3,response3,response3,response3,response3,response3
I want to get this result in php.
$question = "the_question_goes_here"
question1
yes = 2
no = 1
The code must find the unique responses for each question and count how many of each.
Can anyone help?
str_getcsv()
can be used to get a csv string as an array.
Using this you can write a loop over the array which counts up values (in pseudocode):
counts = array;
//Loop over each row
for(row in csvrows){
for(cell in row){
counts[rowHeader][cellValue] = counts[rowHeader][cellValue]+1;
}
}
This should do the trick reading the file contents into PHP
$data= array();
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
foreach ($data as $position => $value) {
if($row == 1) {
$data[$position]['question'] = $value;
$data[$position]['yes'] = 0;
$data[$position]['no'] = 0;
continue;
}
if ($value == 'yes') {
$data[$position]['yes'] = $data[$position]['yes'] + 1
} elseif ($value == 'no') {
$data[$position]['no'] = $data[$position]['no'] + 1
}
}
$row++;
}
fclose($handle);
}
This will return a array which you can read like this