I am writing an e-commerce site and need a good way to calculate product variations. There are products on the site, products can have many groups of options, groups of options can have many options.
So, the Tshirt product has 3 groups of options and options:
Size : Small, Medium, Large,
Color : Red, Blue, Yellow, Black,
Material : Cotton, Nylon,
which creates: little red cotton, little red nylon, little blue cotton, little blue nylon, ... so on and so forth.
I know that the script works, but also that it can be optimized. Can anyone provide a better working example? It should also be possible with recursion ... but I'm in a mental block.
if(count($option_groups) > 1) { // start the variants up foreach($option_groups[0]->get_options() as $option) { $variants[] = array($option); } // go through every other option group to make combos for($x = 1; $x < count($option_groups); $x++) { $combos = array(); foreach($variants as $variant) { $new = array(); foreach($option_groups[$x]->get_options() as $option) { $tmp = $variant; $tmp[] = $option; $new[] = $tmp; } $combos[] = $new; } $variants = array(); foreach($combos as $combo) { foreach($combo as $tmp) { $variants[] = $tmp; } } } }
This is not very time sensitive, but I would like to have a more convenient code number, which is pretty rude.
Also this problem (I feel that this is not the original problem, many carts do it) have a name? I have not dealt with the Google issue for this issue.
EDIT This is what I came to, based on a profitphp solution, but supporting my objects instead of giving me options for one option, combined as a string. All thanks Profitphp!
private function _possible_combos($groups, $prefix = array()) { $result = array(); $group = array_shift($groups); foreach($group->get_options() as $selected) { if($groups) { $tmp = $prefix; $tmp[] = $selected; $result = array_merge($result, $this->_possible_combos($groups, $tmp)); } else { $tmp = $prefix; $tmp[] = $selected; $result[] = $tmp; } } return $result; }