Foreach循环+递归

时间:2014-04-28 11:52:42

标签: php recursion foreach combinations

我试图以更灵活的方式放置此代码,因此无论$ sets数组的大小如何,它都可以工作。我想它可以通过递归完成,但无法找到正确的php语法。

$sets = array(
                array(0, 1, 2, 3),
                array(0, 1, 2, 3),
                array(0, 1, 2, 3),
                array(0, 1, 2, 3)
                );

$combinations = array();

foreach($sets[0] as $s1)
    foreach($sets[1] as $s2)
        foreach($sets[2] as $s3)
            foreach($sets[3] as $s4)
                $combinations[] = array($s1, $s2, $s3, $s4);

print_r($combinations);

1 个答案:

答案 0 :(得分:1)

你可以像这样递归。输出与循环相同

<?php
$sets = array(
    array(0, 1, 2, 3),
    array(0, 1, 2, 3),
    array(0, 1, 2, 3),
    array(0, 1, 2, 3)
);

function get_combinations($sets, &$combinations = array(), &$row = array()) {
    if (count($sets) == 0) {
        $combinations[] = $row;
        return $combinations;
    }
    foreach ($sets[0] as $s) {
        $row[] = $s;
        get_combinations(array_slice($sets, 1), $combinations, $row);
        array_pop($row);
    }
    return $combinations;
}

$combinations = get_combinations($sets);

print_r($combinations);