Php 比较两个数组以找到评估结果
我想比较以下两个阵列:Php 比较两个数组以找到评估结果,php,arrays,Php,Arrays,我想比较以下两个阵列: Array ( [0] => stdClass Object ( [question_id] => 1 [answer_id] => 21 ) [1] => stdClass Object ( [question_id] => 3 [answer_id] => 33
Array
(
[0] => stdClass Object
(
[question_id] => 1
[answer_id] => 21
)
[1] => stdClass Object
(
[question_id] => 3
[answer_id] => 33
)
[2] => stdClass Object
(
[question_id] => 3
[answer_id] => 36
)
[3] => stdClass Object
(
[question_id] => 3
[answer_id] => 38
)
[4] => stdClass Object
(
[question_id] => 6
[answer_id] => 49
)
)
Array
(
[0] => stdClass Object
(
[question_id] => 3
[answer_id] => 38
)
[1] => stdClass Object
(
[question_id] => 3
[answer_id] => 37
)
[2] => stdClass Object
(
[question_id] => 3
[answer_id] => 33
)
[3] => stdClass Object
(
[question_id] => 1
[answer_id] => 22
)
[4] => stdClass Object
(
[question_id] => 6
[answer_id] => 49
)
)
一个数组是评估的正确答案,另一个数组是用户输入的答案
如何将这两个数组与另一个乘积进行比较,该乘积显示问题id以及布尔值,以判断它们是否正确
我目前遇到以下问题:
- 有些问题有多种答案
- 问题的顺序不一样,正确的顺序是第二个数组,它并不总是以数字顺序排列
- 我希望这是一个适合您的解决方案
首先,我从上面重新创建了您的对象:
class AnswerObject {
public $question_id=0;
public $answer_id=0;
function __construct($q,$a){
$this->question_id=$q;
$this->answer_id=$a;
}
}
$obj_student_vals = array(new AnswerObject(1,21), new AnswerObject(3,33), new AnswerObject(3,36), new AnswerObject(3,38), new AnswerObject(6,49));
$obj_answer_key = array(new AnswerObject(1,22), new AnswerObject(3,33), new AnswerObject(3,37), new AnswerObject(3,38), new AnswerObject(6,49));
现在,我提供的解决方案如下,并从上面的代码继续:
$flat_student_vals = array();
$flat_answer_key = array();
// flatten student vals to multi-dimensional array
// e.g. array('3'=>array(33,36,38),'6'=>array(49),'1'=>array(21))
foreach($obj_student_vals as $obj){
if(!array_key_exists($obj->question_id,$flat_student_vals))
$flat_student_vals[$obj->question_id]=array();
$flat_student_vals[$obj->question_id][]=$obj->answer_id;
}
// flatten answer key to multi-dimensional array
// e.g. array('1'=>array(22),'3'=>array(33,37,38),'6'=>array(49))
foreach($obj_answer_key as $obj){
if(!array_key_exists($obj->question_id,$flat_answer_key))
$flat_answer_key[$obj->question_id]=array();
$flat_answer_key[$obj->question_id][]=$obj->answer_id;
}
// the results for this student
$student_results = array();
// when we compare arrays between student vals and answer key,
// the order doesn't matter. the array operator `==` is only concerned
// with equality (same keys/value pairs), not identity (in same order and of same type)
foreach($flat_student_vals as $qid=>$vals){
$student_results[$qid]=($vals == $flat_answer_key[$qid]);
}
print_r($student_results);
我的代码中的注释是相当不言自明的。底线是,为了有效地比较学生对答案键的反应,您需要将两个原始对象数组展平为简单的多维数组