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

前端 未结 8 921
野性不改
野性不改 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:43

    Here is recursive solution:

    function combinations($arrays, $i = 0) {
        if (!isset($arrays[$i])) {
            return array();
        }
        if ($i == count($arrays) - 1) {
            return $arrays[$i];
        }
    
        // get combinations from subsequent arrays
        $tmp = combinations($arrays, $i + 1);
    
        $result = array();
    
        // concat each array from tmp with each element from $arrays[$i]
        foreach ($arrays[$i] as $v) {
            foreach ($tmp as $t) {
                $result[] = is_array($t) ? 
                    array_merge(array($v), $t) :
                    array($v, $t);
            }
        }
    
        return $result;
    }
    
    print_r(
        combinations(
            array(
                array('A1','A2','A3'), 
                array('B1','B2','B3'), 
                array('C1','C2')
            )
        )
    );
    

提交回复
热议问题