/** * Update a student document's 'answers' field with new saved answers. */ private static function saveStudentAnswers(Application $application) { $studentId = $application->getStudentId(); $questions = $application->getQuestions(); if (count($questions) == 0) { return; } // Retrieves the question-answer pairs. $answers = StudentModel::getAnswers($studentId); // Loop through $questions, replace answer for the corresponding question // in $answers, or append to $answers if it is not in $answers. $answersHash = arrayToHashByKey($answers, '_id', 'index'); foreach ($questions as $question) { $questionId = $question['_id']; $newAnswer = $question['answer']; if (isset($answersHash[$questionId . ''])) { $index = $answersHash[$questionId . '']; $answers[$index]['answer'] = $newAnswer; } else { $answers[] = ['_id' => $questionId, 'answer' => $newAnswer]; } } StudentModel::replaceAnswers($studentId, $answers); }