100 PHP array merge I defined a json data Key-value pair. K represents Key V represents Values.
Values with \ r \ n (line break)
That is to say, I want to merge two PHP arrays. If K and Value are exactly the same, I will ignore one. if K is the same and V is different, I will merge V. The Value is also merged, get the array from slpit and then take an intersection
[
{'K': '11111111', 'V': 'v11111 \ r \ nV11112 \ r \ nV11113 '},
{'K': 'k22222 ', 'V': 'v22222 '},
{'K': 'k33333, 'V': 'v33333 '},
{'K': 'k44444', 'V': 'v44443 \ r \ nv44444 '}
]
PHP json_decode function to get the array
Second json
[
{'K': '11111111', 'V': 'v111111111 '},
{'K': 'k33333, 'V': 'v33333 '},
{'K': 'k44444', 'V': 'v44444 \ r \ nv44445 \ r \ nv44446 '},
{'K': 'k55555', 'V': 'v55555 '}
]
Result:
[
{'K': '11111111', '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 '}
]
That is, K
How can we achieve this?
Reply to discussion (solution)
If the intersection is not set, the number
No one is here.
$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"}]