首页 >后端开发 >php教程 >100分PHP数组合并

100分PHP数组合并

WBOY
WBOY原创
2016-06-23 13:52:331056浏览

我定义了一对json数据 键值对的方式 K 代表Key  V代表Values 
values带有\r\n(换行符)
也就是说我想将两个PHP数组进行合并,将K和Value完全相同就忽略一个,如果K相同,V不同,就将V进行合并,值的合并方式也是,同slpit得到数组,然后取一个交集
[
{'K':'k111111','V':'v11111\r\nV11112\r\nV11113'},
{'K':'k22222','V':'v22222'},
{'K':'k33333,'V':'v33333'},
{'K':'k44444','V':'v44443\r\nv44444'}
]
PHP json_decode 函数之后得到数组
第二个json
[
{'K':'k111111','V':'v11111'},
{'K':'k33333,'V':'v33333'},
{'K':'k44444','V':'v44444\r\nv44445\r\nv44446'},
{'K':'k55555','V':'v55555'}
]
得到的结果:
[
{'K':'k111111','V':'v11111\r\nV11112\r\nV11113'},
{'K':'k22222','V':'v22222'},
{'K':'k33333,'V':'v33333'},
{'K':'k44444','V':'v44443\r\nv44444\r\nv44445\r\nv44446'},
{'K':'k55555','V':'v55555'}
]
也就是说K
请问  各位大神们,如何实现


回复讨论(解决方案)

错了  不取交集,取数量多的那个

没人  来人啊 大神们啊

$a =<<< 'JSON'[{'K':'k111111','V':'v11111\r\nV11112\r\nV11113'},{'K':'k22222','V':'v22222'},{'K':'k33333','V':'v33333'},{'K':'k44444','V':'v44443\r\nv44444'}]JSON;$a = str_replace("'", '"', $a);$a = json_decode($a, 1);$b =<<< 'JSON'[{'K':'k111111','V':'v11111'},{'K':'k33333','V':'v33333'},{'K':'k44444','V':'v44444\r\nv44445\r\nv44446'},{'K':'k55555','V':'v55555'}]JSON;$b = str_replace("'", '"', $b);$b = json_decode($b, 1);$res = array();foreach($a as $r) $res[$r['K']] = $r;foreach($b as $r) {  $k = $r['K'];  if(! isset($res[$k])) {    $res[$k] = $r;    continue;  }  if($res[$k]['V'] == $r['V']) continue;  $res[$k]['V'] = join("\r\n", array_unique(array_merge(explode("\r\n", $res[$k]['V']), explode("\r\n", $r['V']))));}echo json_encode(array_values($res));
[{"K":"k111111","V":"v11111\r\nV11112\r\nV11113"},{"K":"k22222","V":"v22222"},{"K":"k33333","V":"v33333"},{"K":"k44444","V":"v44443\r\nv44444\r\nv44445\r\nv44446"},{"K":"k55555","V":"v55555"}]

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn