0
  $answers = array("a", "b", "c", "a", "a", "a");
  $S1Q1 = $_POST['S1Q1'];
  $S1Q2 = $_POST['S1Q2'];

  $S2Q1 = $_POST['S2Q1'];
  $S2Q2 = $_POST['S2Q2'];
  $S2Q3 = $_POST['S2Q3'];
  $S2Q4 = $_POST['S2Q4'];

  $totalValue .= "About OM | Question 01: " . $S1Q1 . "    " . ($S1Q1 == $correct[0]) ? 'Correct' : 'Wrong' . "\n";
  $totalValue .= "        | Question 02: " . $S1Q2 . "    " . ($S1Q2 == $correct[1]) ? 'Correct' : 'Wrong'  . "\n\n";

    $totalValue .= "About EHS         | Question 01: " . $S2Q1 . "    " . ($S2Q1 == $answers[2]) ? 'Correct' : 'Wrong' . "\n";
    $totalValue .= "                   | Question 02: " . $S2Q2 . "    " . ($S2Q2 == $answers[3]) ? 'Correct' : 'Wrong' . "\n";
    $totalValue .= "                   | Question 03: " . $S2Q3 . "    " . ($S2Q2 == $answers[4]) ? 'Correct' : 'Wrong' . "\n";
    $totalValue .= "                   | Question 04: " . $S2Q4 . "    " . ($S2Q2 == $answers[5]) ? 'Correct' : 'Wrong' . "\n\n";

我有上面的php脚本,我可以用什么方法或函数来计算用户在一个循环中有多少正确和多少错误,然后计算百分比?

示例
正确:4
错误:2
总计:6
正确百分比:((4/6) * 100) = 66.666666666% => 将其四舍五入为66%

4

3 回答 3

1

这是一种快速而肮脏的方法来完成它而不改变你已经拥有的东西:

$correct = substr_count($totalValue, "Correct\n");
$wrong = substr_count($totalValue, "Wrong\n");
$total = $correct + $wrong;
$percentage = floor($correct / $total * 100);


也就是说,我认为这可以做得更好。我会将变量作为数组传递。您的帖子字符串看起来像这样:

answers[s1][q1]=a&answers[s1][q2]=b&answers[s2][q1]=c&answers[s2][q2]=a

PHP 会像这样接收它:

answers => Array(
    's1' => Array(
        'q1' => 'a',
        'q2' => 'b'
    ),
    's2' => Array(
        'q1' => 'c',
        'q2' => 'a'
    )
)

看看这个例子。它看起来更长一些,也许更复杂一些,但它更加灵活和可扩展。如果您需要添加任何问题、答案等...您所要做的就是添加相应的数组条目。从长远来看,我认为你会更高兴。

于 2012-09-14T19:28:33.320 回答
1

您必须使用数组而不是不同的变量。例如,而不是这个

$S2Q1 = $_POST['S2Q1'];
$S2Q2 = $_POST['S2Q2'];
$S2Q3 = $_POST['S2Q3'];
$S2Q4 = $_POST['S2Q4'];

做这样的事情:

$s2 = array();
for ($i=1; $i <= 4; $i++) {
    $s2[$i] = $_POST['S2Q'.$i];
}

等等...请原谅可能的语法故障,我已经有一段时间没有做 PHP 了 :-)

于 2012-09-14T19:30:46.213 回答
1

理想情况下,在您的$correct数组中,您将拥有与问题名称相同的键(例如S1Q1S2Q1...等)。这将允许您查找任何问题的答案。然后,您可以遍历问题并查找该问题的正确答案并保持正确的计数。就像是:

//array of correct answers
$correct = array("S1Q1"=>"a", "S1Q2"=>"b", "S2Q1"=>"c", "S2Q2"=>"a", "S2Q3"=>"a", "S2Q4"=>"a");

$correctCount = 0;
$totalValue = '';

//loop through posted answers and check
foreach($_POST as $question=>$answer){
    //check if there is an answer for this question.
    if(array_key_exists($correct, $question)){
        $totalValue .= "Question {$question}: ".($correct[$question]==$answer?'Correct':'Wrong').'<br>';
        $correctCount += ($correct[$question]==$answer?1:0);
    }
}
$pct = round($correctCount/count($correct)*100);

$totalValue .= "You got {$correctCount} out of ".count($correct)." ({$pct}%) answers correct.";
于 2012-09-14T19:46:19.670 回答