【问题标题】:How to calculate comparation percentage of 2 arrays?如何计算2个数组的比较百分比?
【发布时间】:2015-09-23 13:52:44
【问题描述】:

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

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

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

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

【问题讨论】:

  • 为什么不遍历问题数组并为每个正确答案添加一个点?
  • 将键设置为相同的值,然后检查 $answers[1] == $quiz_results[1]。之后得到与正确数量相比的问题总数

标签: php arrays parallel-arrays


【解决方案1】:

浏览答案并将其与问题进行比较。如果它们相同,则增加正确答案计数。

$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%

【讨论】:

    【解决方案2】:

    解决问题的方法略有不同

    $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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 2017-11-12
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多