2011-05-15 111 views
1

的結果我想下面的兩個數組比較:比較兩個數組找到評估

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 
     ) 

) 

一個陣列是正確的答案,評估,另一種是用戶輸入的內容。

如何比較這兩個數組產生另一個顯示question_id以及布爾值是否他們得到它的權利?

我目前遇到以下問題:

  • 一些問題有多個答案給他們。
  • question_id的順序是不一樣的,正確的順序是第二個數組並不總是以數字順序排列。

回答

2

這是我希望爲您工作的解決方案。

首先,我從上面重新創建你的對象:現在

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); 

的意見在我的代碼中是相當不言自明的。最重要的是,爲了有效比較學生對答案的回答,你需要將你原來的兩個對象原始數據平鋪到簡單的多維數組中。