如何比较两个二维数组中的行?
似乎我读到的用于比较数组的每个 PHP 函数(array_diff()
、array_intersect()
等)都会比较数组的存在元素。
给定两个具有相同结构的多维数组,您如何列出值的差异?
示例
Array 1
[User1] => Array ([public] => 1 [private] => 1 [secret] => 1 ) [User2] => Array ([public] => 1 [private] => 0 [secret] => 0 )
Array 2
[User1] => Array ([public] => 1 [private] => 0 [secret] => 1 ) [User2] => Array ([public] => 1 [private] => 0 [secret] => 0 )
Difference
[User1] => Array ([public] => 1 [private] => 0 //this value is different [secret] => 1 )
所以我的结果是 - “在所有用户中,User1 已更改,区别在于 private 是 0 而不是 1。”
It seems that every PHP function I read about for comparing arrays (array_diff()
, array_intersect()
, etc) compares for the existence of array elements.
Given two multidimensional arrays with identical structure, how would you list the differences in values?
Example
Array 1
[User1] => Array ([public] => 1 [private] => 1 [secret] => 1 ) [User2] => Array ([public] => 1 [private] => 0 [secret] => 0 )
Array 2
[User1] => Array ([public] => 1 [private] => 0 [secret] => 1 ) [User2] => Array ([public] => 1 [private] => 0 [secret] => 0 )
Difference
[User1] => Array ([public] => 1 [private] => 0 //this value is different [secret] => 1 )
So my result would be - "Of all the users, User1 has changed, and the difference is that private is 0 instead of 1."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种方法是编写一个函数来执行与此类似的操作。
您可以轻松地扩展该函数以返回两者之间的差异数组。
编辑-这是一个更完善的版本,它更接近您正在寻找的内容:
One way is to write a function to do something similar to this..
You could easily augment that function to return an array of differences in the two..
Edit - Here's a refined version that more closely resembles what you're looking for:
我认为这正是您正在寻找的。
使用示例数据,在外部数组上执行循环,然后每次都对用户使用 array_diff_assoc 。 (请注意,这假设当存在差异时,
array_diff_assoc
返回传入的第二个数组中的值,这似乎是这样做的)。它返回:
I think this does what you're looking for.
Using your sample data, doing a loop on the outer arrays, then using
array_diff_assoc
on the users each time through. (Note, this assumes that when there's a difference,array_diff_assoc
returns the value from the second array passed in, which it seems to do).It returns:
试试这个功能:
Try this function:
如果您正在寻找值的差异,
array_diff_assoc
怎么样。 php 手册 说它“返回一个包含array1 中不存在于任何其他数组中的所有值”并给出以下示例:这是你要找的吗?
If you're looking for differences in the values, how about
array_diff_assoc
. The php manual says it "returns an array containing all the values from array1 that are not present in any of the other arrays" and gives the following example:Is this what you're looking for?