简体   繁体   中英

php compare two associative arrays using array_intersect()

I have two associative arrays. In fact, both are obtained after json decoding.I'm comparing for the presence of same data in both array and obtaining their count. The array_intersect method is giving incorrect result. The count should have been 2 but its giving 4. Please point where I am wrong.

Arrays:

Array ( [question_0] => b [question_1] => b [question_2] => a [question_3] => c )

Array ( [question_0] => a [question_1] => b [question_2] => b [question_3] => c [question_4] => c )

Code:

$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']));

array_intersect is only comparing the values

try to use 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 is comparing keys and values, I think this is what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM