Getting all possible combinations of N elements in X-groups

I have a list of groups that can vary in number, with items in these groups that also vary in quantity. I rack my brains to get all possible combinations of 1 subject from each group.

Bonus: I also need all combinations that do not have all the items in the group.

I saw and did what was mentioned earlier , but this requires knowledge of the number of groups.

To be more specific about what I am doing, I would like to generate accurate priced products based on product options. Here is a list of examples:

Group / Item Example

Thus, it will generate products such as:

-, 500, 4: 0
-, - 500, 4: 1
..

, Group_Item_ID. , :

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

, . , , .

:

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
    )
)
+3
1

:

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;
}
+4

Source: https://habr.com/ru/post/1750856/


All Articles