views:

85

answers:

1

I have a list of Groups that can vary in number, with Items in these groups that also vary in number. I've been racking my head over a way to get all possible combinations of 1 Item from every Group.

Bonus: I also need all combinations of not having every items from a group.

I've seen and done what was mentioned before, but that requires knowing the number of groups to begin with.

To be more specific about what I'm doing, I would like to generate products with exact pricing based off product options. Here's an example list:

Group/Item Example

So it would generate products like:

UV Coating, Qty 500, Color 4:0
UV Coating, Qty 500, Color 4:1
etc...

Each of these Groups has an ID, and each item has a Group_Item_ID. So I can put them in an array such as:

$selections[1][...]  // 1 = Coating
$selections[2][...]  // 2 = Quantity
// ... = all selected Items in group

Hope I explained it well enough. I'm just not able to wrap my head around how to do this when the number of Groups are variable also.

Here's an example array for the groups and their items:

Array
(
[0] => Array
    (
        [0] => 2
        [1] => 3
    )

[1] => Array
    (
        [0] => 10
        [1] => 11
        [2] => 12
    )

[2] => Array
    (
        [0] => 16
        [1] => 17
    )

[3] => Array
    (
        [0] => 19
        [1] => 20
    )
)
+1  A: 

Try this:

function c($groups, $prefix='')
{
    $result = array();
    $group = array_shift($groups);
    foreach($group as $selected) {
        if($groups) {
            $result = array_merge($result, c($groups, $prefix . $selected. ' '));
        } else {
            $result[] = $prefix . $selected;
        }
    }
    return $result;
}
Mewp
I think you're onto something! It seems to only give me the combinations from the last two groups of the array. I'm playing with it right now though and will report back.
drewjoh
Ok, I narrowed it down to the fact that it only gets combinations from the last 2 groups in the array. And it does the combinations multiple times. I'm still working with it though.
drewjoh
Sorry! I made a small mistake in that code, it's fixed now.
Mewp
Genius! You just made my day and saved me so much time! Thank you Mewp!
drewjoh