Cai*_*ero 3 php arrays combinations matrix
假设我有这 3 个数组
$array1 = array(1,2);
$array2 = array(4,5);
$array3 = array(7,8);
Run Code Online (Sandbox Code Playgroud)
我需要这个输出
1 4 7
1 4 8
1 5 7
1 5 8
2 4 7
2 4 8
2 5 7
2 5 8
Run Code Online (Sandbox Code Playgroud)
我的问题之一是我的数组 myght 从 3 到 15 个不同的数组不等,每个 myght 都是空的(我可能会添加一个 0 只是为了不为空)或有很多值。如果我有一个空数组,我还需要将其计为有效列。这些值将用于以特定顺序填充数据库。
有什么办法可以做到这一点吗?
所以首先问题是有多少组合?答案是您必须将每个数组的数量相互乘以。
所以(c = 数量1):
c数组 1 * c数组 2 * ... * c数组 n
并具体针对您的示例:
c数组 1 * c数组 2 * c数组 3 = 2 * 2 * 2 = 8
*1 如果你想知道为什么我选择 c 作为数量,因为 php 中的函数 count()
我们现在如何获得具有数组数量的所有组合?
我们遍历我们已经拥有的所有组合(从一个组合开始,一个“空组合”($combinations = [[]];)),对于每个组合,我们遍历我们的下一个数据数组并将每个组合与每个输入数据组合成一个新组合.
现在我们这样做,直到我们为每个组合获得所需的长度。
举个例子:
Array with the elements (Empty array is '[]'):
[
[1, 2],
[3, 4]
]
Run Code Online (Sandbox Code Playgroud)
//? 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
Run Code Online (Sandbox Code Playgroud)
* NAN:不是数字
因此,正如您在上面的示例中所看到的,我们现在拥有所有数组的长度的所有组合。
但是为了只获得具有所需长度的组合,我们每次迭代都会覆盖结果数组,这样最后只有具有预期长度的组合才会出现在结果数组中。
<?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);
?>
Run Code Online (Sandbox Code Playgroud)
输出:
Array
(
[0] => Array
(
[0] => 1
[1] => 4
[2] => 7
)
//...
[7] => Array
(
[0] => 2
[1] => 5
[2] => 8
)
)
Run Code Online (Sandbox Code Playgroud)
对于关联数组,您只需稍作修改,即:
首先将数组键分配给一个变量array_keys(),例如
$keys = array_keys($data);
Run Code Online (Sandbox Code Playgroud)使用第二个 foreach 循环中的键访问数据数组,表示来自:
foreach ($data[$count] as $v2)
Run Code Online (Sandbox Code Playgroud)
到:
foreach ($data[ $keys[$count] ] 作为 $v2)