php使用array_intersect()比较两个关联数组

时间:2014-06-18 10:09:53

标签: php arrays json associative-array

我有两个关联数组。事实上,两者都是在json解码后获得的。我正在比较两个阵列中相同数据的存在并获得它们的计数。 array_intersect方法给出了错误的结果。计数应该是2但它给出4.请指出我错的地方。

阵列:

  

阵列(       [question_0] => b       [question_1] => b       [question_2] =>一个       [question_3] => c)

     

阵列(       [question_0] =>一个       [question_1] => b       [question_2] => b       [question_3] => C       [question_4] => c)

代码:

$temp = '{"question_0": "b",
        "question_1": "b",
        "question_2": "a",
        "question_3": "c"
        }';

$a = json_decode($temp,true);
print_r($a);

require_once "classes/config.readonly.php";
$data['token'] = '61db6e01cdd809e65e0490158b569b69';
$sql = "SELECT * FROM quiz_logger where token = " . "'" . $data['token'] . "'" ;
$db->query($sql);
while($row = $result->fetch_object() ){
    $answers = $row->data;
}

$ans = json_decode($answers,true);
print_r($ans['data']);

echo count(array_intersect($a, $ans['data']));

1 个答案:

答案 0 :(得分:3)

array_intersect仅比较值

尝试使用array_intersect_assoc http://de2.php.net/manual/en/function.array-intersect-assoc.php

echo count(array_intersect_assoc($a, $ans['data']));

array_intersect_assoc正在比较键和值,我认为这就是你想要的