I have an associative array containing entries that are virtually the same, except the key-value pairs are swapped:
[
[
"partnerA" => "Alice",
"partnerB" => "Alfred"
],
[
"partnerA" => "Alfred",
"partnerB" => "Alice"
],
[
"partnerA" => "Alfred",
"partnerB" => "Brandon"
]
]
I stored the array in a Laravel collection
and tried using ->unique()
$partners = collect($array)->unique();
but the output matches the array feeding in.
How can I remove duplicates like this from an array so each pair is unique no matter if the keys are swapped?
The desired output is:
[
[
"partnerA" => "Alice",
"partnerB" => "Alfred"
],
[
"partnerA" => "Alfred",
"partnerB" => "Brandon"
]
]
Update: What I’ve tried so far that seems to be working…
$size = sizeof($partners);
for($i = 0; $i <= $size; $i++){
$match = $partners[$i];
$needle = ["partnerA" => $match["partnerB"], "partnerB" => $match["partnerA"]];
if(in_array($needle, $partners)){
unset($partners[$i]);
}
}
2
Answers
Try this
Sort the pairs and concatenate the values for a unique key, then filter based on the result.
Output: