Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP嵌套数组组合/置换_Php_Arrays_Combinations_Permutation_Combinatorics - Fatal编程技术网

PHP嵌套数组组合/置换

PHP嵌套数组组合/置换,php,arrays,combinations,permutation,combinatorics,Php,Arrays,Combinations,Permutation,Combinatorics,我以为我的问题已经用VolkerK的答案解决了,但它似乎工作不正常 我想要的是一个函数,它返回嵌套数组中包含的所有可能的值组合 例如,如果我通过 它会回来的 a, a, a, a, a, a b, b, b, a, a, a a, a, b, a, a, a a, b, a, a, a, a b, a, a, a, a, a a, b, b, a, a, a b, b, a, a, a, a b, a, b, a, a, a 下面使用VolkerK的答案的问题是,它只是返回 a, a, a,

我以为我的问题已经用VolkerK的答案解决了,但它似乎工作不正常

我想要的是一个函数,它返回嵌套数组中包含的所有可能的值组合

例如,如果我通过

它会回来的

a, a, a, a, a, a
b, b, b, a, a, a
a, a, b, a, a, a
a, b, a, a, a, a
b, a, a, a, a, a
a, b, b, a, a, a
b, b, a, a, a, a
b, a, b, a, a, a
下面使用VolkerK的答案的问题是,它只是返回

a, a, a, a, a, a
b, b, b, a, a, a
a, a, a, a, a, a
b, b, b, a, a, a
a, a, a, a, a, a
b, b, b, a, a, a
a, a, a, a, a, a
b, b, b, a, a, a
如何修复下面的代码以返回我上面所做的正确组合?(或者您可以编写一个新函数来实现上述功能吗?)

这是一个相当“直截了当”的、不优雅的(或丑陋的,如果你愿意)解决方案,并且不符合你的预期顺序(如果你愿意):

输出:

Array
(
    [0] => a,a,a,a,a,a
    [1] => b,a,a,a,a,a
    [2] => a,b,a,a,a,a
    [3] => b,b,a,a,a,a
    [4] => a,a,b,a,a,a
    [5] => b,a,b,a,a,a
    [6] => a,b,b,a,a,a
    [7] => b,b,b,a,a,a
)

我将您的
[]
语法更改为
array()
,以提供更向后兼容的功能(但匿名函数需要PHP5.3)。

我的JavaScript中有一个可以做到这一点,但它可能被移植到PHP

function P(array $sources)
{
    $result=array();
    $cache=array();
    foreach($sources as $node)
    {
        $cache=$result;
        $result=array();
        foreach($node as $item)
        {
            if(empty($cache))
            {
                $result[]=array($item);
            }
            else
            {
                foreach($cache as $line)
                {
                    $line[]=$item;
                    $result[]=$line;
                }
            }
        }
    }
    return $result;
}
$result=P(array(array('a','b'),array('a','b'),array('a','b'),array('a'),array('a'),array('a')));
print_r(array_map(function($a){return implode(",",$a);},$result));
Array
(
    [0] => a,a,a,a,a,a
    [1] => b,a,a,a,a,a
    [2] => a,b,a,a,a,a
    [3] => b,b,a,a,a,a
    [4] => a,a,b,a,a,a
    [5] => b,a,b,a,a,a
    [6] => a,b,b,a,a,a
    [7] => b,b,b,a,a,a
)