How to generate in PHP all combinations of items in multiple arrays

前端 未结 8 791
野性不改
野性不改 2020-11-22 07:20

I\'im trying to find all combinations of items in several arrays. The number of arrays is random (this can be 2, 3, 4, 5...). The number of elements in each array is random

8条回答
  •  难免孤独
    2020-11-22 07:38

    Here is a code that generates unique combinations from a set of numbers.

    If you have a list of numbers, like 1,3,4,7,12 you can generate sets of X numbers, all unique, no repetitive.

    The first function works in PHP 7.4 or higher, and the second one uses keys to store the values. Both work very well based on the benchmark.

    function get_combos74($map, $size, &$generated = [], $loop = 1, $i = 0, $prefix = [])
    {
        if ($loop == 1) {
            sort($map);
        }
    
        for (; $i < count($map); $i++) {
            if ($loop < $size) {
                get_combos74($map, $size, $generated, $loop + 1, $i + 1, [...$prefix, $map[$i]]);
            } else {
                $generated[] = [...$prefix, $map[$i]];
            }
        }
    
        return $generated;
    }
    
    function get_combosSTR($map, $size, &$generated = [], $loop = 1, $i = 0, $prefix = '')
    {
        if ($loop == 1) {
            sort($map);
        }
    
        for (; $i < count($map); $i++) {
            if ($loop < $size) {
                get_combosSTR($map, $size, $generated, $loop + 1, $i + 1, "$prefix{$map[$i]}:");
            } else {
                $generated["$prefix{$map[$i]}"] = 0;
            }
        }
    
        return $generated;
    }
    

提交回复
热议问题