php if clause inside foreach not retrieving data correctly
Posted
by Mike
on Stack Overflow
See other posts from Stack Overflow
or by Mike
Published on 2010-04-18T21:57:23Z
Indexed on
2010/04/18
22:03 UTC
Read the original article
Hit count: 430
Here's my issue: In my controller, I want to grab user input from a form. I then parse the input, and compare it to database values to ensure I'm grabbing the correct input. I simply want to match the user's answers to the question, grab the user ID, the question ID, and then determine if the answer applies to a multiple choice or checkbox question, or something else. I take those values and insert them into the answer table. Ignore the waiver stuff. I'll test that once I get the answers input correctly.
// add answers and waiver consent records
try {
$answerArray = array();
$waiverArray = array();
// retrieve answers, waiver consents, and the question ID's from form object
foreach ($formData as $key => $value) {
$parts = explode("_", $key);
if ($parts[0] == 'question') {
array_push($answerArray, $value);
}
if ($parts[0] == 'waiverTitle') {
array_push($waiverArray, $value);
}
}
$questions = new Model_DbTable_Questions();
$questionResults = $questions->getQuestionResults($session->idEvent);
foreach ( $questionResults as $qr ) {
if ($qr ['questionType'] == 'multipleChoice' || $qr ['questionType'] == 'checkBox') {
foreach ( $answerArray as $aa ) {
$answerData = $answers->addAnswer ( $lastUserID, $qr ['idQuestion'], null, $aa );
echo count ( $answerData ) . ', ' . $qr ['questionType'] . ', ' . $aa . '<br />';
}
} else {
foreach ( $answerArray as $aa ) {
$answerData = $answers->addAnswer ( $lastUserID, $qr ['idQuestion'], $aa, null );
echo count ( $answerData ) . ', ' . $qr ['questionType'] . ', ' . $aa . '<br />';
}
}
}
}
catch (Zend_Db_Statement_Exception $e)
{
$e->getMessage();
throw $e;
}
From my test data, I expect to get 2 records that match the multiple choice and checkbox criteria, and 1 record for text in the ELSE clause like this:
3, checkbox, 1
3, multipleChoice, 1
3, text, question_2
What I get is a 3x3 Cartesian product, 3 question elements each with the 3 possible answers like this output from the echo statements:
4, checkBox, 1
4, checkBox, 1
4, checkBox, question_2
4, multipleChoice, 1
4, multipleChoice, 1
4, multipleChoice, question_2
4, text, 1
4, text, 1
4, text, question_2
I've tried placing the IF clause inside the inner foreach, but I get the same results. I've been staring at this problem for way too long and cannot see what I'm doing wrong. Your kind assistance would be greatly appreciated. Please let me know if my request requires more clarification.
© Stack Overflow or respective owner