<?php
// Initiate WP
require_once('../../../wp-config.php');  
$wp->init();  
$wp->parse_request();  
$wp->query_posts();  
$wp->register_globals(); 

// Assign current post ID as variable
$current_post = $_POST['post_id'];

// Remove post_id from $_POST
if (array_key_exists('post_id', $_POST)) {
	unset($_POST['post_id']);
}

// Set up new array 
$chosen_ans = array();

$i = 1;
foreach ($_POST as $id => $value) {
	// Add chosen answers into new array
	$chosen_ans[$i] = $value;
	$i++;
}

/**
 * Master array; multidimensional; 
 * This array stores the meta_key, question and answers stored in WP-Admin,
 * the user's submitted answer and the comparison result.
 *
 * Structure:
 * 
 * - meta_key 		[str] 		( e.g. "module_0_questions_3_question" [ 0 = First Repeater, 3 = 3rd Question] )
 * - - question 	[str] 		( e.g. "How clean is your house?" )
 * - - correct 		[bool(int)] ( e.g. 0 = False, 1 = True )
 * - - chosen 		[bool(int)]	( See above )
 * - - result 		[str]		( e.g. "match" if their answer is correct, "no match" if not )
 * 
 * @var array
 */
$q_and_a = array();


/** PARENT REPEATER **/

// check for rows (parent repeater)
if( get_field('module',$current_post) ): ?>
		<?php 

		// loop through rows (parent repeater)
		while( has_sub_field('module',$current_post) ): ?>

				<?php 
				/** SUB REPEATER **/

				// check for rows (sub repeater)
				if( get_sub_field('questions') ): ?>

					<?php 
					$i = 1;
					// loop through rows (sub repeater)
					while( has_sub_field('questions',$current_post) ): 

						?>

						<?php // Set up variables of ACF fields and chosen answers ?>
						<?php $question = get_sub_field('question'); ?>
						<?php $correct_answer = get_sub_field('correct_answer'); ?>
						<?php $chosen_answer = $chosen_ans[$i]; ?>

						<?php
						$sql = "SELECT meta_key
								FROM wp_postmeta
								WHERE post_id = '" . $current_post . "'
								and meta_value = '" . $question . "';";

						$row = $wpdb->get_row($sql,OBJECT);
						?>

						<?php // Check if correct answer is the same as the chosen answer ?>
						<?php if ($correct_answer == $chosen_answer): ?>
							<?php $result = "match"; ?>
						<?php else : ?>
							<?php $result = "no match"; ?>
						<?php endif; ?>

						<?php
							// Create multidimensional array with question as key and
							// answers and result as sub-key => values
						?>
						<?php $q_and_a[$row->meta_key] = array(
												'question'	=> $question,
												'correct'	=> $correct_answer,
												'chosen'	=> $chosen_answer,
												'result'	=> $result
												); ?>

					<?php $i++; endwhile; ?>

				<?php
				endif; 


				/** END SUB REPEATER **/
				?>

		<?php endwhile; ?>
<?php
endif;

/** END PARENT REPEATER **/
?>

<pre>
	<?php print_r($q_and_a); ?>
</pre>