开发者

PHP 2D array_diff / array_intersect for INSERT / UPDATE / DELETE

开发者 https://www.devze.com 2023-02-17 04:43 出处:网络
I have a pair of 2D a开发者_开发问答rrays corresponding to a set of records from a database. One array contains the current records, the other contains the new records.

I have a pair of 2D a开发者_开发问答rrays 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消