[英]Recursive PHP Tree (permutations)
I'm looking to write a function which creates all permutation of a list of arrays (The list is dynamical). 我正在寻找一个函数,它创建一个数组列表的所有排列(列表是动态的)。 Now I found 2 articles, http://dannyherran.com/2011/06/finding-unique-array-combinations-with-php-permutations/ and Finding cartesian product with PHP associative arrays .
现在我发现了2篇文章http://dannyherran.com/2011/06/finding-unique-array-combinations-with-php-permutations/和使用PHP关联数组查找笛卡尔积 。 But I don't want to store them as multiple arrays, I want to add each array to each possibility so I can use them later.
但我不想将它们存储为多个数组,我想为每种可能性添加每个数组,以便稍后使用它们。
In fact I want to multiply each array with the other. 实际上我想将每个数组与另一个数组相乘。
For example: 例如:
$array = array(
array(
1,
2
),
array(
'A',
'B',
'C'),
array(
'I',
'II')
);
In this form: 以这种形式:
Array
(
[0] => Array
(
[0] => 1
[1] => Array
(
[0] => Array
(
[0] => A
[1] => Array
(
[0] => I
[1] => II
)
)
[1] => Array
(
[0] => B
[1] => Array
(
[0] => I
[1] => II
)
)
[2] => Array
(
[0] => C
[1] => Array
(
[0] => I
[1] => II
)
)
)
)
[1] => Array
(
[0] => 2
[1] => Array
(
[0] => Array
(
[0] => A
[1] => Array
(
[0] => I
[1] => II
)
)
[1] => Array
(
[0] => B
[1] => Array
(
[0] => I
[1] => II
)
)
[2] => Array
(
[0] => C
[1] => Array
(
[0] => I
[1] => II
)
)
)
)
)
I think this big example made my problem clear. 我认为这个重要的例子让我的问题变得清晰。 For this type of array I created a function: foreach ($array[1] as $value) { $return1[] = array($value, $array[2]);
对于这种类型的数组,我创建了一个函数:foreach($ array [1] as $ value){$ return1 [] = array($ value,$ array [2]); }
}
foreach ($array[0] as $value) {
$return[] = array($value, $return1);
}
print_r($return);
Now I want to create this function inside a recursive function (so it becomes dynamical) but I got stuck. 现在我想在递归函数中创建这个函数(因此它变得有动力)但我卡住了。 I wanted to pass the amount of arrays to the function and then iterate.
我想将数量的数量传递给函数然后迭代。
function createTree($array, $loops=3){
$b = $array[$loops-2];
foreach ($b as $v) {
$return[] = array($v, createTree($return, $loops-1));
}
print_r($return);
}
Maybe there is a total other solution to multiply the arrays? 也许有另外一个解决方案来增加阵列? But the function which isn't recursive is easy for me, but making it recursive...
但是不是递归的函数对我来说很容易,但是让它递归...
Thanks for your help 谢谢你的帮助
function createTree($array){
switch(count($array)) {
case 0:
die('Illegal argument.');
case 1:
return $array[0];
default:
$lastArray = array_pop($array);
$subArray = createTree($array);
foreach ($lastArray as $item) {
$return[] = array($item, $subArray);
}
return $return;
}
}
var_dump(createTree(array_reverse($array)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.