PHP 比较两个数组?
我正在尝试比较数据库中的两个条目,因此当用户进行更改时,我可以获取两个数据库条目并比较它们以查看用户更改的内容,因此我会得到类似于以下内容的输出:
User Changed $fieldName
从 $originalValue
到 $newValue
我已经研究过这个并遇到了 array_diff
但它没有给我我需要的输出格式。
在我继续编写一个执行此操作的函数并将其作为一个漂亮的 $mtextFormatDifferenceString
返回之前,有人能给我指出一个已经执行此操作的解决方案的方向吗?
我不想重新发明轮子..
I'm trying to compare two entries in a database, so when a user makes a change, I can fetch both database entries and compare them to see what the user changed, so I would have an output similar to:
User changed $fieldName
from $originalValue
to $newValue
I've looked into this and came across array_diff
but it doesn't give me the output format I need.
Before I go ahead and write a function that does this, and returns it as a nice $mtextFormatDifferenceString
, can anyone point me in the direction of a solution that already does this?
I don't want to re-invent the wheel..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您需要“从 $originalValue 到 $newValue”,我将继续选择两行,将它们放入关联数组中,然后遍历键,保存不相等的行。有点像:
我知道你问的是预制轮子的存在,但我觉得解决方案非常简单。
?>
Since you require "from $originalValue to $newValue", I would go ahead and select the two rows, put them in assoc arrays, then foreach through the keys, saving the ones that aren't equal. Kind of like:
I realize you were asking about the existence of pre-built wheels but I felt the solution was pretty simple.
?>
虽然您没有定义所需的格式,但众所周知的
diff
算法可能适合您。 Google一下PHP diff算法
,我相信你会找到一些建议。Although you didn't define what format you needed, but well-known
diff
algorithm is probably for you. Google forPHP diff algorithm
and you'll find some suggestions I am sure.您可以使用 array_diff_assoc 获取更改后的值 ($newValue),然后只需使用键 ($fieldName) 查找原始值 $originalValue 并以您想要的任何格式输出它
You could get the changed values ($newValue) with array_diff_assoc and then just use the keys ($fieldName) to find the original value $originalValue and output it in anyformat you want