Answer the question
In order to leave comments, you need to log in
How to select unique combinations from an array?
I have an array, for example:
$array = array('orange', 'apple', 'banana', 'pine');
array('orange', 'apple');
array('orange', 'banana');
array('orange', 'pine');
array('orange', 'apple', 'banana');
array('orange', 'apple', 'pine');
array('apple', 'banana');
array('apple', 'pine');
array('apple', 'banana', 'pine');
array('banana', 'pine');
Answer the question
In order to leave comments, you need to log in
One of the many solutions:
stackoverflow.com/questions/4279722/php-recursion-...
$a = array('orange', 'apple', 'banana', 'pine');
$len = count($a);
$list = array();
for ($i = 1; $i < (1 << $len); $i++) {
$c = [];
for ($j = 0; $j < $len; $j++) {
if ($i & (1 << $j)) {
$c[] = $a[$j];
}
}
$list[] = $c;
}
print_r($list);
Mm ... in fact, the task is reduced to building an enumeration + checking the occurrence of an element in a set.
To check, it is worth defining some function that associates an array with a certain string (in fact, some kind of hashing function), and the string will be unique for each possible array.
Then the uniqueness can be controlled by checking the unique strings of the current value that already exist in some array.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question