I have the following array
$values = ['P1', 'P2', 'P3', ['P1', 'P2'], ['P1', 'P3'], ['P2', 'P3'], ['P1', 'P2', 'P3']];
From this array I want to pick all combinations without a value repeating itself and you can only pick distinct number of items which in this case will be 3.
For example it should be like this
$result1 = ['P1', 'P2', 'P3'];
$result2 = ['P1', ['P2', 'P3']];
$result3 = ['P2', ['P1', 'P3']];
$result4 = ['P3', ['P1', 'P2']];
$result5 = [['P1', 'P2', 'P3']];
.
.
.
.and so on
What I have done until now
- Looked at many combinations questions like these Question, Question.
- Looked at Chase's Twiddle algorithm here.
The above approaches seems like they will not work for me. So I started doing my own code like below, but I am a little lost.
$values = [['P1'], ['P2'], ['P3'], ['P1', 'P2'], ['P1', 'P3'], ['P2', 'P3'], ['P1', 'P2', 'P3']];
$result = [];
$i = 0;
foreach ($values as $key => $value) {
$result[$i][] = $value;
$restArray = array_diff_key($values, array_flip([$key]));
foreach ($restArray as $v) {
foreach ($v as $val) {
if (!in_array($val, $result[$i])) {
$result[$i][] = $v;
}
}
}
$i++;
}