How do I get the elements from the two arrays below where the value of email
key only exists once from either of the list, and then merge their keys?
Say, I got two arrays:
$arr1 = [
['email' => '[email protected]', 'name' => 'John Doe'],
['email' => '[email protected]', 'name' => 'Johnny Sins'],
['email' => '[email protected]', 'name' => 'Jose Alvarado']
];
$arr2 = [
['email' => '[email protected]', 'country' => 'Japan'],
['email' => '[email protected]', 'country' => 'China'],
['email' => '[email protected]', 'country' => 'Korea'],
];
The final result should be:
[
['email' => '[email protected]', 'name' => 'John Doe'],
['email' => '[email protected]', 'name' => 'Johnny Sins', 'country' => 'Korea'],
];
I tried the following, but I’m stuck on merging the key:
$merged = array_merge($arr1, $arr2);
$result = array_filter($merged, function($value) use($merged) {
return array_count_values(array_column($merged, 'email'))[$value['email']] < 3;
});
3
Answers
After misunderstanding your question, I’ve made another attempt. The complication is that you need to check for duplicates in each array and not the joint results.
This first checks for duplicates and creates a list of the ones that should be excluded…
What it then does is it builds a list of the non-duplicate values, merging in new values as it encounters existing values, creating a new element where it doesn’t…
My approach used in this demo was first determining on both arrays if there are any duplicated email. Such check will produce an array containing all the emails that shouldn’t be taken into account as the marge of the duplicated emails coming from both arrays.
Then you can use such array when filtering the first and second array so that it will be returned only the entries NOT having any email contained in the above cited array of not allowed emails.
In the end it’s a matter of returning the filtered arrays merged.
References:
https://www.php.net/manual/en/function.array-column
https://www.php.net/manual/en/function.array-count-values
https://www.php.net/manual/en/function.array-filter
https://www.php.net/manual/en/function.array-keys
https://www.php.net/manual/en/function.in-array
https://www.php.net/manual/en/function.array-merge
Demo:
https://onlinephp.io/c/c638f
Until there is further clarification from the asker (and a better representing set of sample data), I am going assume:
Code: (Demo)
If either array may have disqualifying rows, then the following approach will sanitize and merge the two arrays on their shared email value with a low time complexity.
Code: (Demo)