2011-03-17 50 views
0

我有一對2D數組對應於數據庫中的一組記錄。用於INSERT/UPDATE/DELETE的PHP 2D array_diff/array_intersect

一個數組包含當前記錄,另一個包含新記錄。

我想要一個優雅的通用解決方案來排序這些數組,以便我知道哪些新記錄要INSERT或UPDATE,以及哪些當前記錄要刪除。我相信這一定是普通的行爲,但是不需要大量嵌套數組循環的答案就可以逃脫我。

我想理想情況下一個二維數組交點會得到UPDATE記錄,而一個2D array_diff則是INSERT/DELETE記錄。

+2

請分享一些代碼。 「代碼片段勝過千言萬語」 – DhruvPathak 2011-03-17 10:40:50

回答

3

如果我給你的權利,我建議是這樣的:

$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 

你現在有3個陣列,所有的數據,我想的名字清楚地告訴他們該怎麼做。請記住,這些函數返回其第一參數數據,所以

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

array_intersect_key($new_ids, $old_ids)將返回數據,並array_intersect_key($old_ids, $new_ids)將返回的數據,你必須再次尋找新的價值。不要亂參錯誤順序。

+0

謝謝 - 是的,這實際上就是我所做的。我想我星期五想過了!唯一的另一個補充是將交叉數組與舊數組進行比較以檢查UPDATE是否必要。 – 2011-03-21 11:03:21