PHP 比较两个数组?

发布于 2024-08-25 17:35:25 字数 372 浏览 4 评论 0原文

我正在尝试比较数据库中的两个条目,因此当用户进行更改时,我可以获取两个数据库条目并比较它们以查看用户更改的内容,因此我会得到类似于以下内容的输出:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

穿越时光隧道 2024-09-01 17:35:25

由于您需要“从 $originalValue 到 $newValue”,我将继续选择两行,将它们放入关联数组中,然后遍历键,保存不相等的行。有点像:

$fields = array_keys($row1);
$changedFields = array();

foreach ($fields as $field) {
    if ($row1[$field] != $row2[$field]) {
        $changedFields[] = $field;
    }
}

我知道你问的是预制轮子的存在,但我觉得解决方案非常简单。

?>

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:

$fields = array_keys($row1);
$changedFields = array();

foreach ($fields as $field) {
    if ($row1[$field] != $row2[$field]) {
        $changedFields[] = $field;
    }
}

I realize you were asking about the existence of pre-built wheels but I felt the solution was pretty simple.

?>

红衣飘飘貌似仙 2024-09-01 17:35:25

虽然您没有定义所需的格式,但众所周知的 diff 算法可能适合您。 Google一下PHP diff算法,我相信你会找到一些建议。

Although you didn't define what format you needed, but well-known diff algorithm is probably for you. Google for PHP diff algorithm and you'll find some suggestions I am sure.

我三岁 2024-09-01 17:35:25

您可以使用 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文