如何计算2个阵列的比较百分比?

时间:2015-09-23 13:52:45

标签: php arrays parallel-arrays

如果我在PHP或javascript中有2个数组,最好是在PHP中,如何获得正确答案的百分比?

所以,我有这两个数组,我想将测验结果与正确的答案进行比较并获得百分比分数:

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

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

2 个答案:

答案 0 :(得分:3)

运行答案并将其与问题进行比较。如果它们是相同的增量,则为正确的答案计数。

h1 {
    &:extend(.display1);

    border-bottom:solid 0.1rem @divider;
    color:@primaryText;
    margin-bottom:2.4rem;
    padding-bottom:0.7rem;
}

答案 1 :(得分: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