0

I have a pair of 2D arrays corresponding to a set of records from a database.

One array contains the current records, the other contains the new records.

I would like an elegant generic solution to sort these arrays so that I know which of the new records to INSERT or UPDATE, and which of the current records to DELETE. I'm sure this must be common behaviour, but an answer that doesn't require lots of nested array looping escapes me.

I think ideally a 2D array intersection would get the UPDATE records, and a 2D array_diff the INSERT / DELETE records.

1
  • 2
    share some code please. "A code snippet is worth a thousand words" Commented Mar 17, 2011 at 10:40

1 Answer 1

3

If I got you right I would suggest something like this:

$old_ids = array();
foreach ($old as $row) {
    $old_ids[$row['id']] = $row;
}
$new_ids = array();
foreach ($new as $row) {
    $new_ids[$row['id']] = $row;
}

$insert = array_diff_key($new_ids, $old_ids);
    //^^^Returns all records of $new_ids that aren't present in $old_ids
$update = array_intersect_key($new_ids, $old_ids);
    //^^^Returns all records of $new_ids that were present in $old_ids
$delete = array_diff_key($old_ids, $new_keys);
    //^^^Returns all records of $old_ids that aren't present in $new_ids

You now have 3 arrays with all data, and I think names clearly tell what to do with them. Just keep in mind that these functions return data of their first arguments, so

array_intersect_key($new_ids, $old_ids) != array_intersect_key($old_ids, $new_ids)

as array_intersect_key($new_ids, $old_ids) will return new data, and array_intersect_key($old_ids, $new_ids) will return old data, and you'll have to look up for new values again. Don't mess arguments order by mistake.

1
  • Thank you - yes this is effectively what I did. I think I was over thinking it on Friday! the only other addition would be to compare the intersect array with the old array to check the UPDATE was necessary. Commented Mar 21, 2011 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.