有多少种组合?
那么首先的问题是有多少种组合?答案是你必须将每个数组的数量相乘。
So (c = amount1):
carray 1 * carray 2 * ... * carray n
具体针对您的示例:
carray 1 * carray 2 * carray 3 = 2 * 2 * 2 = 8
*1 And if you wonder why I chose c for amount, because of the function count() in php
将所有组合组合在一起
我们现在如何获得与我们拥有的数组数量的所有组合?
我们循环遍历我们已经拥有的所有组合(从一个组合开始,一个“空组合”($combinations = [[]];
)),对于每个组合,我们都会遍历下一个数据数组,并将每个组合与每个输入数据组合成一个新的组合。
现在我们这样做,直到获得每个组合所需的长度。
举个例子:
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] //desired length 2 as we have 2 arrays
- [1] + 4 │ -> [1,4] //desired length 2 as we have 2 arrays
- [2] + 3 │ -> [2,3] //desired length 2 as we have 2 arrays
- [2] + 4 │ -> [2,4] //desired length 2 as we have 2 arrays
//↑ All combinations here
* NAN: not a number
正如您在上面的示例中看到的,我们现在拥有所有组合,其长度等于我们拥有的所有数组的数量。
但为了仅获得具有所需长度的组合,我们每次迭代都会覆盖结果数组,以便最终只有具有预期长度的组合位于结果数组中。
Code:
<?php
$array1 = array(1,2);
$array2 = array(4,5);
$array3 = array(7,8);
$combinations = [[]];
$data = [
$array1,
$array2,
$array3,
];
$length = count($data);
for ($count = 0; $count < $length; $count++) {
$tmp = [];
foreach ($combinations as $v1) {
foreach ($data[$count] as $v2)
$tmp[] = array_merge($v1, [$v2]);
}
$combinations = $tmp;
}
print_r($combinations);
?>
output:
Array
(
[0] => Array
(
[0] => 1
[1] => 4
[2] => 7
)
//...
[7] => Array
(
[0] => 2
[1] => 5
[2] => 8
)
)
对于关联数组,您只需要做一些轻微的修改,即:
-
首先将数组键分配给变量array_keys()
, e.g.
$keys = array_keys($data);
-
使用第二个 foreach 循环中的键来访问数据数组,意味着来自:
foreach ($data[$count] as $v2)
to:
foreach ($data[$keys[$count]] as $v2)