views:

87

answers:

3

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 accross 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..

A: 

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.

Col. Shrapnel
A: 

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

Javier Parra
+1  A: 

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.

?>

webbiedave
You know when you can't see the wood for the trees...I took your code and built on it to give me the desired output.Thanks!
Sjwdavies
I know it all too well :) Glad I could help.
webbiedave