Home > OS >  Remove A|B duplicates from associative array in Laravel
Remove A|B duplicates from associative array in Laravel

Time:10-25

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]);
    }
}

CodePudding user response:

Sort the pairs and concatenate the values for a unique key, then filter based on the result.

$unique_keys = array_keys(array_unique(array_map(
    function($a){
        sort($a);
        return implode("", $a);
    },
    $partners
)));

$res = array_filter(
    $partners,
    function($a)use($unique_keys) {
        return in_array($a, $unique_keys);
    },
    ARRAY_FILTER_USE_KEY
);

var_dump($res);

Output:

array(2) {
  [0]=>
  array(2) {
    ["partnerA"]=>
    string(6) "Alfred"
    ["partnerB"]=>
    string(5) "Alice"
  }
  [2]=>
  array(2) {
    ["partnerA"]=>
    string(6) "Alfred"
    ["partnerB"]=>
    string(7) "Brandon"
  }
}

CodePudding user response:

Try this

$results = [
[
    "partnerA" => "Alfred",
    "partnerB" => "Alice"
],
[
    "partnerA" => "Alfred",
    "partnerB" => "Alice"
]
];

$newArray = [];
foreach($results as $result) {
    if(is_array($result)) {
        foreach($result as $key => $output) {
            $newArray[$key] = $output;
        }
    }
}
print_r(array_unique($newArray));
  • Related