我正在编写PHP测验应用程序,并且在评分机制方面遇到了一些麻烦。具体来说,我有两个数组,我正在比较,以确定答案是否正确。
我想验证一个数组的所有值都在另一个数组中找到。例如,如果正确答案
Array
(
[0] => Proprietary user community
[1] => Surveys
[2] => Voice
[3] => Online chat
[4] => Web
[5] => Email
[6] => Social media
)
用户提供的答案是:
Array
(
[0] => Surveys
[4] => Online chat
[6] => Email
)
系统返回错误,因为尚未提供所有正确的值。同样,如果用户提供的答案如下所示:
Array
(
[0] => Proprietary user community
[1] => Surveys
[2] => Voice
[3] => Online chat
[4] => Web
[5] => Email
[6] => Social media
[7] => Phone
[8] => Live chat
)
如果提供了额外的答案,答案是正确的。
有什么想法吗?我一直在考虑使用array_intersect()
,但必须有一个更优雅的解决方案。
非常感谢任何帮助!
答案 0 :(得分:2)
只需与数组相交并比较大小。
$answer_key = array(/* your answer key here */);
$user_answers = array(/* user answers here */);
$intersection = array_intersect($answer_key, $user_answers);
if (count($answer_key) === count($intersection)) {
// winner, winner, chicken dinner
} else {
// fail
}
答案 1 :(得分:1)
使用array_intersect()有什么问题?
<?php
$arr1 = array("a" => "green", "red");
$arr2 = array("b" => "green", "yellow", "red");
$result = count(array_intersect($array1, $array2)) === count(arr1.count);
?>
答案 2 :(得分:0)
数组差异对此更好:
http://php.net/manual/en/function.array-diff.php
if (empty(array_diff($correctArray, $userAnswers))) {
// correct
} else {
// incorrect
}