为什么这个小循环失败了?

时间:2017-05-30 17:22:00

标签: php arrays count compare associative-array

我的循环如下:

foreach( $user_answers_for_current_quiz as $question_id => $answer ) {
    if( $answer == $correct_answers[$question_id] ) {
        $score = $score + 1;
    }
}

提供给此循环的值如下: -

$user_answers_for_current_quiz = [ 190 => "option_2, 183 => "option_1"];
$correct_answers = [ 183 = "option_1", 190 => "option_2" ];
$score = 0;

我观察到的奇怪行为是,在第一次迭代中,PHP无法计算出

的值
$correct_answers[ $question_id ]

并将其计算为NULL。但是,在第二次迭代中,它会准确计算值并更新$score

我检查了PHP手册,发现数组'key'可以是一个整数。我不确定是什么导致我的循环失败?

我已经花了3个多小时试图解决这个问题,如果有人能指出正确的方向,我会非常感激。感谢您提前的时间。

---------------- +++ ADDENDUM +++ -----------

以下是从实际运行时间复制的值:

$user_answers_for_current_quiz = [ 62 => "2", 60 => "4", 57 => "2", 54 => "4", 52 => "3" ];
$correct_answers = [ 52 => "3", 54 => "4", 62 => "2", 60 => "4", 57 => "2" ];

代码 -

foreach( $user_answers_for_current_quiz as $question_id => $answer ) {
    if( $answer == $correct_answers[$question_id] ) {
        $score = $score + 1;
        print_r('Score'.$question_id." = ".  $score . "<br>");
    }
}

程序打印的内容是:Score52 = 1

我发现循环无法评估'if'条件;我不知道为什么。非常感谢帮助。

进一步编辑。从xdebug添加屏幕截图: enter image description here

2 个答案:

答案 0 :(得分:1)

您的问题语法不正确。无论如何,如果没有错误的语法,您的代码应该可以工作。我在我的服务器上对此进行了测试,似乎可以正常工作。

<?php


$user_answers_for_current_quiz = [ 190 => "option_2", 183 => "option_1"];
$correct_answers = [ 183 => "option_1", 190 => "option_2" ];
$score = 0;

foreach( $user_answers_for_current_quiz as $question_id => $answer ) {
    if( $answer == $correct_answers[$question_id] ) {
       $score = $score + 1;
        print_r('Score'.$question_id." = ".  $score . "<br>");
     }
}

 print_r('Last Score: '.  $score);


?>

这是输出:

Output of debugging code

答案 1 :(得分:0)

以下是您应该使用的方法:

$user_answers_for_current_quiz = [ 62 => "2", 60 => "4", 57 => "2", 54 => "4", 52 => "3" ];
$correct_answers = [ 52 => "3", 54 => "4", 62 => "2", 60 => "4", 57 => "2" ];

$score=sizeof(array_intersect_assoc($correct_answers,$user_answers_for_current_quiz));
echo $score;
// outputs: 5

array_intersect_assoc()保留所有精确的键值对匹配,无论它们在数组中的顺序/位置如何,sizeof()计算保留的元素数量。这会将您的方法细化为单行,无需在每次迭代时有条件地覆盖/递增$score变量。