What I need
I need all possible pairs of n elements without duplicates. Let's say I've these arrays:
$arr1 = [2, 4, 6, 7];
$arr2 = [6, 5, 4, 11];
$arr3 = [22, 1, 5, 8];
$final = [
'a' => $arr1,
'b' => $arr2,
'c' => $arr3
];
What I now need is:
$pairs = [
'ab' => [$arr1, $arr2],
'ac' => [$arr1, $arr3],
'bc' => [$arr2, $arr3]
];
What I got
I come until this point:
function getPairs($array) {
$n = count($array);
$finalArray = [];
$i = 0;
foreach ($array as $a) {
for ($x = $n-1; 0 <= $x; $x--) {
if ($i != $x) {
$finalArray[] = [$array[$i], $array[$x]];
}
}
$i++;
}
return $finalArray;
}
And then:
$arr1 = [2, 4, 6, 7];
$arr2 = [6, 5, 4, 11];
$arr3 = [22, 1, 5, 8];
$merged = [$arr1, $arr2, $arr3];
$pairs = getPairs($merged);
There are two problems with my approach:
- The loop produces
$x = 0
,$i = 1
and later$i = 1
,$x = 0
, which results and a duplicated array. - I don't get the keys (
ab
,ac
,cb
) with this.
Similiar to this question but with array keys: Get all the combinations of N elements of multidimensional array