note 68925 deleted from ref.array by levim
| From: | levim@php.net | Date: | Tue, 06 May 2014 22:10:27 +0000 |
| Subject: | note 68925 deleted from ref.array by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-199468@lists.php.net to get a copy of this message | ||
Note Submitter: sergio at {NO_SPAM_PLEASE]inservibile dot org
----
In a pratical problem, I was involved in a system of queries giving the behaviour of all
combinations of some parameters. How to write those queries?
The problem was to generate automatically every possible combination of those parameters. I
didn't find a function and I wrote it.
(Naturally, a different way could be to build a binary sequence, but I find this function more
compact and useful).
So, consider an array of objects and suppose to need all possibile combinations of those objects.
Here is the function, that could be useful for some folk.
Enjoy.
<?php
function combinations($elements) {
if (is_array($elements)) {
/*
I want to generate an array of combinations, i.e. an array whose elements are arrays
composed by the elements of the starting object, combined in all possible ways.
The empty array must be an element of the target array.
*/
$combinations=array(array()); # don't forget the empty arrangement!
/*
Built the target array, the algorithm is to repeat the operations below for each object
of the starting array:
- take the object from the starting array;
- generate all arrays given by the target array elements merged with the current object;
- add every new combination to the target array (the array of arrays);
- add the current object (as a vector) to the target array, as a combination of one
element.
*/
foreach ($elements as $element) {
$new_combinations=array(); # temporary array, see below
foreach ($combinations as $combination) {
$new_combination=array_merge($combination,(array)$element);
# I cannot merge directly with the main array ($combinations) because
I'm in the foreach cycle
# I use a temporary array
array_push($new_combinations,$new_combination);
}
$combinations=array_merge($combinations,$new_combinations);
}
return $combinations;
} else {
return false;
}
}
?>
To test the function:
<?php
$elements=array('bitter','sour','salty','sweet');
print_r(combinations($elements));
?>
The exemple was suggested in 6th century BC.
See why on: http://en.wikipedia.org/wiki/Combinatorics#Overview_and_history