array_diff 比较两个关联数组
我对 array_diff 行为感到困惑,
为什么 diff 数组上不存在流派? 你知道如何解决这个问题吗?
-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));
我的结果:
Array
(
[contry] => us
)
但我期望:
Array
(
[value01] => 0,
[genre] => 1,
[contry] => us,
);
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,
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信您想使用
array_diff_assoc
http ://www.php.net/manual/en/function.array-diff-assoc.php
I believe you want to use
array_diff_assoc
http://www.php.net/manual/en/function.array-diff-assoc.php
array_diff
对数组的值进行操作,并忽略键。因为第一个数组中
genre
的值为1
,这意味着如果任何键出现1
值 在第二个数组中,则genre
键将从第一个数组中删除。看看没有键的数组,你就会明白我的意思。您本质上有两个值列表:
['0','v2','1','text','us','1']
和['v1',' v2','0','文本','加拿大','1']
。第一个列表中唯一未出现在第二个列表中的值是'us'
。我猜您可能想看看 array_key_diff () 或 array_diff_assoc()。
array_diff
operates on the values of the array, and ignores the keys.Because the value of
genre
in your first array is1
, that means that if the value1
occurs for any key in the second array, then thegenre
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().
在多深度关联数组的情况下,
array_diff_assoc
将导致数组到字符串转换异常,例如像这样的数组:对于这些类型,我创建了一个通用的自定义函数,您可以使用它:
与
不同>array_diff_assoc
它返回布尔值
array_diff_assoc
will cause Array to string conversion exception in case of multi depth associative arrays, for example arrays like these:For these types I have created a custom function which is generic, you can use that:
Unlike
array_diff_assoc
it returnsboolean