比较嵌套数组

时间:2017-01-25 09:44:42

标签: php arrays compare

我有这些数组,第一个代表答案给用户一个问卷,第二个代表每个问卷的正确答案:

$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
  }
}

注意:两个数组中的每个键都代表questionID,除了我在评论中提到的那些。因此,例如,questionID 46将answerID 84作为正确答案,而questionID 48具有88和91的正确答案,因此在这种情况下,键0,1是简单的数组索引。

我要做的是比较两个阵列并检查答案 (questionID)匹配每个questionID。我怎样才能做到这一点?我尝试使用array_diff(),但我收到了错误

$result = array_diff($correct_answers, $given_answers);

Severity: Notice

Message: Array to string conversion

2 个答案:

答案 0 :(得分:1)

  

所有答案都应该与正确答案完全匹配,所以如果我有   即使是一个错误我也有错误

使用以下方法:

$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

答案 1 :(得分:1)

更好的方法是递归调用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);

我希望这能解决你的问题。