这应该适合你:
那么这段代码有什么作用呢?
1.一共有多少种组合?
因此,首先的问题是有多少种组合,答案是您必须将每个数组的数量相互相乘。
So (c = amount1):
carray 1 * carray 2 * ... * carray n
具体针对您的示例:
carray 1 * carray 2 = 3 * 3 = 9
*1 And if you wonder why I chose c
for amount, because of the function count()
in php
2. 获取所有组合
现在我们如何获得所有数组长度的所有组合?
非常简单,我们只是循环遍历所有组合(一开始只是一个空组合([] == array()
)) 我们已经有了下一个数组,直到我们得到我们想要的长度,在这种情况下是最后一个数组的最后一次迭代。
举个例子:
Array with the elements (Empty array is '[]'):
[
[1, 2],
[3, 4]
]
//new combinations for the next iteration
|
array NAN*:
Combinations:
- [] | -> []
|
array 1 [1,2]: -------------
| |
Combinations: v v
- [] + 1 | -> [1]
- [] + 2 | -> [2]
|
array 2 [3,4]: -------------
| |
Combinations: v v
- [] + 3 | -> [3]
- [] + 4 | -> [4]
- [1] + 3 | -> [1,3]
- [1] + 4 | -> [1,4]
- [2] + 3 | -> [2,3]
- [2] + 4 | -> [2,4]
//^ All combinations here
* NAN: not a number
正如您在上面的示例中看到的,我们现在拥有所有组合,其长度等于我们拥有的所有数组的数量。
但为了仅获得具有所需长度的组合,我们每次迭代都会覆盖结果数组,以便最终只有具有预期长度的组合位于结果数组中。
code:
<?php
$data = [
35 => ["green", "red", "brown"],
36 => ["fox", "house", "dog"]
];
$combinations = [[]];
$comKeys = array_keys($data);
for ($count = 0; $count < count($comKeys); $count++) {
$tmp = [];
foreach ($combinations as $v1) {
foreach ($data[$comKeys[$count]] as $v2)
$tmp[] = $v1 + [$comKeys[$count] => $v2];
}
$combinations = $tmp;
}
print_r($combinations);
?>
output:
Array
(
[0] => Array
(
[35] => green
[36] => fox
)
[1] => Array
(
[35] => green
[36] => house
)
[2] => Array
(
[35] => green
[36] => dog
)
[3] => Array
(
[35] => red
[36] => fox
)
[4] => Array
(
[35] => red
[36] => house
)
[5] => Array
(
[35] => red
[36] => dog
)
[6] => Array
(
[35] => brown
[36] => fox
)
[7] => Array
(
[35] => brown
[36] => house
)
[8] => Array
(
[35] => brown
[36] => dog
)
)