2015-09-23 2 views
-1

Как получить процент правильных ответов, если у меня есть 2 массива в PHP или javascript, желательно на PHP?Как рассчитать процент сравнения двух массивов?

Итак, у меня есть эти два массива, и я хочу, чтобы сравнить результат викторины с правильными ответами и получить процент балл:

$quiz_results = array('q1' => 'no', 
        'q2' => 'yes', 
        'q3' => 'no', 
) 

$answers = array(1 => 'yes', 
        2 => 'no', 
        3 => 'yes' 
) 
+0

Почему не перебираем массив вопросов и добавить точку за каждый правильный ответ? – feeela

+0

Установите ключи на одно и то же значение и просто проверьте, $ answer [1] == $ quiz_results [1]. После этого получите общее количество вопросов по сравнению с правильной суммой – Crecket

ответ

3

Выполнить через ответы и сравнить их с вопросами. Если они имеют одинаковый прирост, правильный подсчет ответов.

$quiz_results = array('q1' => 'yes', 
        'q2' => 'yes', 
        'q3' => 'no', 
); 
$answers = array(1 => 'yes', 
        2 => 'no', 
        3 => 'yes' 
); 

$totalquestions = count($answers); 
$correct = 0; 
foreach($answers as $key => $answer){ 
    //q + the key should do it. Its easier if they are the same obviously 
    if($answer == $quiz_results['q'.$key]){ 
     // correct 
     $correct++; 
    } 
} 

echo 100/$totalquestions * $correct; //returns 33.333333% 
1

несколько иной подход к проблеме

$rating=array_merge(
    array_fill_keys(range(0,32), 'Poor'), 
    array_fill_keys(range(33,65), 'Moderate'), 
    array_fill_keys(range(66,89), 'Above average'), 
    array_fill_keys(range(90,100), 'Excellent') 
); 
$quiz_results = array(
    'q1' => 'no', 
    'q2' => 'yes', 
    'q3' => 'no' 
); 
$answers = array(
    1 => 'yes', 
    2 => 'no', 
    3 => 'yes' 
); 

$i=1; 
$score=0; 

while($answer = current($quiz_results)) { 
    $score += ($answer==$answers[ $i ]) ? 1 : 0; 
    echo 'Question [ '.$i.' ]: You answered: '.$answer.', The correct answer is: '.$answers[ $i ].'<br />'; 
    $i++; 
    next($quiz_results); 
} 
echo 'Score: '.$score.'/'.count($quiz_results).' - '.round(abs(($score/count($quiz_results)) * 100),2).'%'; 
echo '<br />Rating: '. $rating[ ceil(abs(($score/count($quiz_results)) * 100)) ]; 

Выведет:

You answered: no, The correct answer is: yes 
You answered: yes, The correct answer is: no 
You answered: no, The correct answer is: yes 
Score: 0/3 - 0% 
Rating: Poor 
Смежные вопросы