示例
$asName = 'ids';
$newData = [
['ids'=>'100001','value'=>1],
['ids'=>'100003','value'=>2],
['ids'=>'100004','value'=>4],
['ids'=>'100005','value'=>5],
];
$oldData = [
['ids'=>'100001','value'=>1],
['ids'=>'100002','value'=>2],
['ids'=>'100003','value'=>3],
['ids'=>'100004','value'=>4],
];
$c = aliasArrayDiff($newData, $oldData,$asName);
var_dump($c);
代码
function aliasArrayDiff(array $newData,array $oldData,
string $asName='goods_id', array $attach=[])
{
$extractArrayAs = function($data, $asName){
$_d = [];
array_map(function($d) use (&$_d, $asName){$_d[]=$d[$asName];}, $data);
return $_d;
};
$_newAsData = $extractArrayAs($newData, $asName);
$_oldAsData = $extractArrayAs($oldData, $asName);
$_asNewData = [];
array_map(function($item) use (&$_asNewData, $asName){
$_asNewData[$item[$asName]] = $item;
}, $newData);
$_delete = array_diff($_oldAsData, $_newAsData);
$_delete = array_values($_delete);
$_newAdd = array_diff($_newAsData, $_oldAsData);
$_newAdd = array_values($_newAdd);
$_update = [];
array_map(function($item)
use (&$_update, $_asNewData, $asName) {
if (isset($_asNewData[$item[$asName]]) &&
array_diff_assoc(array_values($item), array_values($_asNewData[$item[$asName]]))) {
$_update[] = $item[$asName];
}
}, $oldData);
$_data = ['add'=>[],'delete'=>[],'update'=>[],'unchanged'=>[]];
$_mergeData = array_merge($oldData, $newData);
foreach ($_mergeData AS $i => $item)
{
$item = array_merge($item, $attach);
$_keyValue = $item[$asName];
if (in_array($_keyValue, $_delete)) {
$_data['delete'][] = $item;
}elseif (in_array($_keyValue, $_newAdd)) {
$_data['add'][] = $item;
}elseif (in_array($_keyValue, $_update)) {
$_data['update'][$_keyValue] = $item;
}else{
$_data['unchanged'][$_keyValue] = $item;
}
}
$_data['update'] = array_values($_data['update']);
$_data['unchanged'] = array_values($_data['unchanged']);
return $_data;
}
|