将数组内数组应答键调整为简单数组应答键

时间:2015-02-24 01:07:01

标签: php arrays

这是我用来评估数据库驱动的测验的脚本。它有效 - 但只有在只有一个问题有多个答案的情况下(#10,在这种情况下)。

if (isset($_POST)):

$totalCorrect = 0;
$answers = array(1 => 'A', 2 => 'banana', 3 => 'C', 4 => 'D', 5 => 'A', 6 => 'C', 7 => 'C', 8 => 'C', 9 => 'B', 10 => array('A','B','C'));

foreach ($answers as $num => $answer):

    $question = 'q'.$num;

    if(is_array($answer) && isset($_POST[$question])){
        $ans_cnt = count($answer);
        $ans_value = (1 / $ans_cnt);

        $post_cnt = count($_POST[$question]);

        //find matches between answer array and post array
        $matches = array_intersect($answer,$_POST[$question]);
        $good_answers = count($matches);
        //Get bad answer count, which be be subtracted from overall  score
        $bad_answers  = 0;
        foreach($_POST[$question] as $post_answer):
            if(!in_array($post_answer,$answer)):
                $bad_answers++;
            endif;
        endforeach;

 if($good_answers ==3 && $bad_answers==0){
 $result = 1;
 }else{
 $result = 0;
}

        if(($post_cnt != $ans_cnt) || ($post_cnt == $ans_cnt &&  $ans_cnt != count($matches))){
            $result = $result * $ans_value;
            $totalCorrect = $totalCorrect + $result;    
        }else{            
            $totalCorrect++;        
        }

    }elseif(isset($_POST[$question]) && strtolower($_POST[$question])  === strtolower($answer)){
        $totalCorrect++;
    }
 endforeach;

 $pct = round( (($totalCorrect/count($answers)) * 100), 0);
 echo $totalCorrect.' correct ('.$pct.'%)';
endif;

我想修改它,这样我就可以用多个答案创建任意数量的问题,即使我仍然需要手动编写每个答案密钥。这是我现在正在使用的脚本,虽然我还没能使它工作。

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
 $qa = $_POST['q'];
 $correct = 0;

 $answers = array(1 => array('A'), 
             2 => array('banana'), 
             3 => array('C'), 
             4 => array('D'), 
             5 => array('A'), 
             6 => array('C'), 
             7 => 'C',
             8 => 'C', 
             9 => 'B', 
             10 => array('A','B','C'));
$total = count($answers);
foreach($answers as $k => $v){
    if(is_array($v)){
        if($qa[$k] === $answers[$k]){
            $correct++;
        }
    }else{
        if($qa[$k] === $answers[$k]){
            $correct++;
        }
    }
 }
 $grade= ($correct/count($answers))*100;
 echo"<p>Score $grade %</p>";
}

我一直在来回,尝试或多或少地将第二个脚本导入第一个脚本,反之亦然,更改各种值等,但我无法使其工作。有谁知道编写代码的正确方法?

1 个答案:

答案 0 :(得分:1)

使用array_diff() http://php.net/manual/en/function.array-diff.php

foreach($answers as $k => $v){
    if(is_array($v)){
        if(array_diff($qa[$k], $v) == array()){
            $correct++;
        }
    } else if($qa[$k] === $v){
        $correct++;
    }
 }