我有这些数组,第一个数组代表用户在调查问卷中给出的答案,第二个数组代表每个问卷的正确答案:
$given_answers => array(3) {
[46] => string(2) "82"
[47] => string(2) "86"
[48] => array(2) {
[0] => string(2) "88" // key is not questionID here
[1] => string(2) "89" // key is not questionID here
}
}
$correct_answers => array(3) {
[46] => int(84)
[47] => int(86)
[48] => array(2) {
[0] => int(88) // key is not questionID here
[1] => int(91) // key is not questionID here
}
}
注意:两个数组中的每个键都代表问题ID,除了我在评论中提到的这些。例如,问题 ID 46 的正确答案为答案 ID 84,问题 ID 48 的正确答案为 88 和 91,因此在这种情况下,键 0、1 是简单的数组索引。
我想做的是比较两个数组并检查答案是否正确 (questionID) 匹配每个 QuestionID。我该怎么做?我尝试使用
array_diff()
但出现错误
$result = array_diff($correct_answers, $given_answers);
Severity: Notice
Message: Array to string conversion
所有答案都应该与正确答案完全匹配,所以如果我有 即使有一个错误我也有错误
使用以下方法:
$given_answers = [
46=> "82",
47=> "86",
48=> ["88", "89"],
];
$correct_answers = [
46=> "84",
47=> "86",
48=> ["88", "91"],
];
$all_matched = true;
foreach ($given_answers as $k => $ans) {
if (!is_array($ans)) {
if ($correct_answers[$k] != $ans) { // comparing primitive values
$all_matched = false;
break;
}
} else {
// comparing arrays for equality
if (!empty(array_diff($ans, $correct_answers[$k]))) {
$all_matched = false;
break;
}
}
}
var_dump($all_matched); // false
更好的方法是递归调用 array_diff 函数,如下所示,
$array = array(
46=>86,
47=>86,
48 => [
0=> 88,
1 => 89
]
);
$array1 = [
46 => 64,
47 => 86,
48 => [
0 => 88,
1 => 91
]
];
function array_diff_assoc_recursive($array1, $array2)
{
$difference = array();
foreach ($array1 as $key => $value) {
if (is_array($value)) {
if (!isset($array2[$key]) || !is_array($array2[$key])) {
$difference[$key] = $value;
} else {
$new_diff = array_diff_assoc_recursive($value, $array2[$key]);
if (!empty($new_diff)) {
$difference[$key] = $new_diff;
}
}
} else if (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
$difference[$key] = $value;
}
}
return $difference;
}
$arr = array_diff_assoc_recursive($array,$array1);
print_r($arr);
我希望这能解决您的问题。
递归不是必需的,因为简单的字符串和子数组可以通过
array_udiff_assoc()
求值。具有无序元素的子数组将被视为不同,但松散相等的子数组值将被视为相同。 当然,如果结果数组为空,则数组被视为“相等”。 演示
$given_answers = [
46 => "82",
47 => "86",
48 => ["88", "89"],
49 => "83",
50 => ["51", "49"],
51 => ["1", "2", "3"],
];
$correct_answers = [
46 => "84",
50 => ["49", "51"],
47 => "86",
49 => "86",
48 => ["88", "91"],
51 => ["1", 2, "3"],
];
var_export(
array_udiff_assoc(
$correct_answers,
$given_answers,
fn($a, $b) => $a <=> $b
)
);
输出:
array (
46 => '84',
50 =>
array (
0 => '49',
1 => '51',
),
49 => '86',
48 =>
array (
0 => '88',
1 => '91',
),
)