I have created a simple multiple choice questionnaire using HTML, PHP and SQL, which when submitted, adds numeric values to a table which each represent specific answers to each of the questions.
For example, I have four questions, and one submitted form may appear in my database cell as '0,1,3,1' (So answered the first option '0' for Question 1, and '1' for Question 2 etc;).
I'm now trying to output that data, and count how many people have selected which answer on each question.
How can I loop over that data in the table and get PHP to increment some kind of array each time so that I eventually ha开发者_如何学Pythonve a count of 'This many people answered X for Question X'.
I'm a little confused! Thanks in advanced.
/* EDIT */
My database layout is simple (possibly where I'm going wrong), it's simply:
Questionnaire ID | Results
1 --------------------0,1,3,2
(Couldn't get the table to layout well but hopefully that's clear)
As for what I have tried so far, not much as I couldn't think what to do.
I've got two for loops, one nested inside the other, that execute relative to the amount of questions I have, which create empty arrays for each question and answer.
Now I need to fill these arrays with counts of how many times each answer has been selected.
Why not do it in the original SQL, ie.
"select question, answer, count(answer)
group by question, answer"
This should then output a list of your questions, the answers that were chose, and how many times...
You should refactor your database to support these kind of queries.
But the following code may help in the meantime:
// 2 fake questionnaire copies. You will want to fetch these from your database
$test = array("1,2,3", "1,1,1");
// Sum up the answers
foreach ($test as $copy) {
$answer_array = explode(",", $copy);
foreach ($answer_array as $question => $answer) {
$sum[$question][$answer]++;
}
}
// Display the result
foreach ($sum as $question => $answer_sum) {
echo "Question {$question}\n";
foreach ($answer_sum as $answer => $sum) {
echo "\t{$answer} answered {$sum} times\n";
}
}
精彩评论