简体   繁体   English

PHP比较两个数组?

[英]PHP Compare Two Arrays?

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 用户将$fieldName$originalValue更改$fieldName $newValue

I've looked into this and came across array_diff but it doesn't give me the output format I need. 我研究了这个问题,并遇到了array_diff但是它没有提供我需要的输出格式。

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? 在继续编写执行此操作的函数并将其返回为一个不错的$mtextFormatDifferenceString ,谁能指出我已经执行此操作的解决方案的方向?

I don't want to re-invent the wheel.. 我不想重新发明轮子。

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. 由于您需要“从$ originalValue到$ newValue”,因此我将继续选择两行,将它们放入assoc数组中,然后遍历各个键,保存不相等的键。 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. 我意识到您在询问是否存在预制车轮,但我认为解决方案非常简单。

?> ?>

Although you didn't define what format you needed, but well-known diff algorithm is probably for you. 尽管您没有定义所需的格式,但是著名的diff算法可能适合您。 Google for PHP diff algorithm and you'll find some suggestions I am sure. Google for PHP diff algorithm ,您肯定会找到一些建议。

您可以使用array_diff_assoc获取更改后的值($ newValue),然后仅使用键($ fieldName)查找原始值$ originalValue并以所需的任何格式输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM