Not sure if this question is a duplicate in need of removal, but I couldn't find the answer elsewhere so I'll have a go at asking.
I've got a 2d array that looks as follows:
Array
(
[0] => Array
(
[0] => dave
[1] => jones
[2] => [email protected]
)
[1] => Array
(
[0] => john
[1] => jones
[2] => [email protected]
)
[2] => Array
(
[0] => bruce
[1] => finkle
[2] => [email protected]
)
)
I'd like to remove those with duplicate emails. So in the above example I'd like to just remove either [][0] or [][2]. I'm not worried about checking against names or anything like that, I just need the sub arrays to be deduplicated based on a single value.
At the moment I have something like this
if(is_array($array) && count($array)>0){
foreach ($array as $subarray) {
$duplicateEmail[$subarray[2]] = isset($duplicateEmail[$subarray[2]]);
unset($duplicateEmail[$subarray[2]]);
}
}
but it just ain't right. Any help appreciated.
The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.
A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.
A quick solution which uses the uniqueness of array indexes:
$newArr = array();
foreach ($array as $val) {
$newArr[$val[2]] = $val;
}
$array = array_values($newArr);
Notice 1: As visible from above, the last match for an email address is used instead of the first. This can be changed by replacing the second line with
foreach (array_reverse($array) as $val) {
Notice 2: The indexes in the resulting array are somewhat mixed up. But I guess this doesn't matter...
Much Simpler Solution.
$unique = array_map('unserialize', array_unique(array_map('serialize', $array)));
echo "<pre>";
print_r($unique);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With