Reputation: 2297
I have an array
array:2 [▼
0 => array:2 [▼
0 => 159
1 => 158
]
1 => array:2 [▼
0 => 159
1 => 158
]
2 => array:2 [▼
0 => 158
1 => 159
]
]
I want to delete the duplicate ones and the duplicate in reverse order. For example index 0
and index 1
has the same values 159 and 158
also same in order like 0 => 159
and 1 => 158
. I want to delete either index 1
or 0
. Since it is same. And if you noticed index 2
. it has the same value only difference is the order 0 => 158
and 1 => 159
I also want to delete this since it is the same pair values. How can I do that if that array is $remove_arr
So since I will delete index 2
and either index 0
or 1
there should only be one index left.
Upvotes: 2
Views: 912
Reputation: 44526
Here's a shorter solution:
$data = [[158, 159], [158, 159], [159, 158]];
$unique = array_unique(array_map(function ($item) {
sort($item); return $item;
}, $data), SORT_REGULAR);
dump($unique); // This will output [[158, 159]]
This solution sorts the contents of the level 2 arrays. So after sorting, the last value will also become [158, 159]
so it can be correctly evaluated by array_unique
as a duplicate.
Upvotes: 2
Reputation: 26153
count(array_intersect()) gets the amount of the same items in the array. When it equal the array lenght, remove one of them
$remove_arr = [
[158, 159],
[158, 159],
[159, 158]
];
for($i = count($remove_arr)-1; $i >= 0 ; $i--) {
$j = $i-1;
while ($j >= 0) {
if (count(array_intersect($remove_arr[$i],$remove_arr[$j])) == count($remove_arr[$i]))
{ unset($remove_arr[$i]); break; }
else $j--;
}
}
print_r($remove_arr);
Upvotes: 1