array_diff to compare two associative arrays
I'm confusing array_diff behavior
why genre don't exist on diff array? Do you know how to resolve the matter?
-code
<?php
$array1 = array
(
'value01' =开发者_如何学运维> '0',
'value02' => 'v2',
'genre' => '1',
'type' => 'text',
'contry' => 'us',
'data' => '1',
);
$array2 = array
(
'value01' => 'v1',
'value02' => 'v2',
'genre' => '0',
'type' => 'text',
'contry' => 'canada',
'data' => '1',
);
print_r(array_diff($array1,$array2));
My result:
Array
(
[contry] => us
)
But I expect:
Array
(
[value01] => 0,
[genre] => 1,
[contry] => us,
);
I believe you want to use array_diff_assoc
http://www.php.net/manual/en/function.array-diff-assoc.php
array_diff
operates on the values of the array, and ignores the keys.
Because the value of genre
in your first array is 1
, that means that if the value 1
occurs for any key in the second array, then the genre
key will be removed from the first array.
Look at your arrays without the keys, and you'll see what I mean. You essentially have two lists of values, ['0','v2','1','text','us','1']
and ['v1','v2','0','text','canada','1']
. The only value from the first list that doesn't appear in the second is 'us'
.
I'm guessing you'll probably want to have a look at array_key_diff() or array_diff_assoc().
精彩评论