请求数组数据和原有数据做对比(相同的更新,不同的追加,并去除重复数据)
demo: 现在是请求过来的是,二维数组数据,本地的也是二维数组数据,app的包名是唯一的,通过对比本地原有的数据,把包名,作为数组key,然后去和新来的数据做对比,如果新来数据的已存在,并且版本号大于原有数据,那么此应用版本更新,并且去除重复数据 , 反之(不更新),如果新来数据,不存在,那么两个数组追加,最后返回json数据!
实现方法一:通过遍历去做if判断,简单,执行效率高!
/**
* 接入数据和本地原有数据做对比,返回json更新数据
* @param $requestAppData 上报的app数据
* @param $localAppData 本地已上报过的app数据
* @return json
*/
function returnReportAppsJsonData($requestAppData, $localAppData){
foreach($localAppData as $key => $v){
$localListData[$v['p']]['p']= $v['p'];
$localListData[$v['p']]['v']= $v['v'];
$localListData[$v['p']]['f']= $v['f'];
}
foreach($requestAppData as $key => $val){
$requestAppList[$key]['p'] = $val['p'];
$local_data = $localListData[$val['p']];
//本地的包名 == 请求过来的包名,做版本比较
if ($local_data['p'] == $val['p']) {
if ($local_data['v'] < $val['v']) {
$v = $val['v'];
unset($localListData[$val['p']]);
} else {
$v = $local_data['v'];
unset($localListData[$val['p']]);
}
$requestAppList[$key]['v'] = $v;
$requestAppList[$key]['f'] = $local_data['f'];
} else {
$requestAppList[$key]['v'] = $val['v'];
$requestAppList[$key]['f'] = $val['f'];
}
//包名为空 删掉
if ($val['p'] == "" || empty($val['p'])) {
unset($requestAppList[$key]);
}
}
$mergeData = @array_merge_recursive($localListData, $requestAppList);
$k = 0;
foreach($mergeData as $key2 => $md){
$mergeData2[$k]['p'] = $md['p'];
$mergeData2[$k]['v'] = $md['v'];
$mergeData2[$k]['f'] = $md['f'];
$k++;
}
return json_encode($mergeData2);
}
实现方法二:通过php原有函数,做交集和差级,对比,在拼接,执行效率略慢!
输入代码
/**
* 接入数据和本地原有数据做对比,返回json更新数据
* @param $requestAppData 上报的app数据
* @param $localAppData 本地已上报过的app数据
* @return json
*/
function returnReportAppsJsonData($requestAppData, $localAppData){
foreach($localAppData as $key => $v){
$localListData[$v['p']]['p']= $v['p'];
$localListData[$v['p']]['v']= $v['v'];
$localListData[$v['p']]['f']= $v['f'];
}
foreach($requestAppData as $key => $val){
$requestAppList[$val['p']]['p']= $val['p'];
$requestAppList[$val['p']]['v']= $val['v'];
$requestAppList[$val['p']]['f']= $val['f'];
}
//交集和本地数据做对比处理
$interData = @array_intersect_assoc($requestAppList, $localListData);
$k = 0;
if ($interData) {
foreach($interData as $ik => $iv){
$ivData[$k]['p'] = $iv['p'];
$ivData[$k]['f'] = $iv['f'];
if ($ik == $localListData[$ik]['p']) {
if ($iv['v']<$localListData[$ik]['v']) {
$v = $localListData[$ik]['v'];
} else {
$v = $iv['v'];
}
$ivData[$k]['v'] = $v;
}
$k++;
}
}else{
$ivData = array();
}
//新增数据和已存在数据-差级处理 & 反比
$dki = 0;
$diffData = @array_diff_assoc($requestAppList, $localListData);
$diffData2 = @array_diff_assoc($localListData, $requestAppList);
if ($diffData || $diffData2) {
$diff_data = @array_merge_recursive($diffData, $diffData2);
foreach($diff_data as $dk => $dv){
$dvData[$dki]['p'] = $dv['p'];
$dvData[$dki]['v'] = $dv['v'];
$dvData[$dki]['f'] = $dv['f'];
$dki++;
}
}else{
$dvData = array();
}
$mergeData = @array_merge_recursive($dvData, $ivData);
// print_r($mergeData);
// die;
return json_encode($mergeData);
}
热门评论
您好,我是出版社的编辑,请问您有兴趣出书吗?