多维数组排列组合

2017-08-01 10:57  196人阅读  评论 (0)
Tags: php

排列组合1

function show($options, $depth = 0) {
    static $stack;
    if ($depth === 0) {
        $stack = [];
    }
    foreach ($options[$depth] as $v) {
        $stack[$depth] = $v;
        if ($depth + 1 == count($options)) {
            echo implode(",", $stack), "\n";
        } else {
            show($options, $depth + 1);
        }
    }
}

$options = [
    [0, 1, 2],
    [0, 1, 2],
    [0, 1, 2],
];

show($options);

排列组合2

function show(&$result, &$stack, $options, $depth = 0) {
    foreach ($options[$depth] as $v) {
        $stack[$depth] = $v;
        if ($depth + 1 == count($options)) {
            $result[] = implode(",", $stack);
        } else {
            show($result, $stack, $options, $depth + 1);
        }
    }
}

$options = [
    [0, 1, 2],
    [0, 1, 2],
    [0, 1, 2],
];

show($result, $stack, $options);
var_dump($result, $stack);