获取多维数组的所有变体

时间:2013-11-02 16:42:29

标签: php arrays

我有一个数组,例如:

Array
(
    [2] => Array
        (
            [3] => Yes
            [4] => No
        )
    [4] => Array
        (
            [28] => Maroon
            [29] => Red
            [30] => Dark Blue
            [31] => Grey
            [32] => Pastel Blue
            [33] => Yellow
            [34] => Green
        )    
    [7] => Array
        (
            [265] => Var 1
            [266] => Var 2
            [267] => Var 3
            [268] => Var 4
        )    
    [87] => Array
        (
            [1888] => 1800h x 450w x 450d (1845N)
        )    
)

我想获得产品选项的所有独特的数组变体,例如

Array
(
    [2] => 3
    [4] => 28
    [7] => 265
    [87] => 1888
)
Array
(
    [2] => 3
    [4] => 29
    [7] => 265
    [87] => 1888
)

等等。 我添加了我需要添加的所有细节,但显然我需要添加更多细节。

1 个答案:

答案 0 :(得分:0)

<?php
function comb($a){
    $out = array();
    if (count($a) == 1) {
        $x = array_shift($a);
        foreach ($x as $v) $out[] = array($v);
        return $out;
    }
    foreach ($a as $k => $v){
        $b = $a;
        unset($b[$k]);
        $x = comb($b);
        foreach ($v as $v1){
            foreach ($x As $v2) 
            $out[] = array_merge(array($v1), $v2);
        }
    }
    return $out;
}


$test = array(array('red', 'blue', 'green'),array('small', 'med', 'large'),array('car', 'truck', 'van'));

$x = comb($test);
print_r($x);
?>