php – 如何从多个数组中获取所有组合?
|
假设我有这3个数组
$array1 = array(1,2); $array2 = array(4,5); $array3 = array(7,8); 我需要这个输出 1 4 7 1 4 8 1 5 7 1 5 8 2 4 7 2 4 8 2 5 7 2 5 8 我的一个问题是我的数组myght从3到15个不同的数组不等,每个myght都是空的(我可能会添加0只是为了空)或者有很多值. 有什么方法可以做到这一点吗?
有多少组合?
那么首先要问有多少种组合?答案是你必须将每个阵列的数量相互增加. 所以(c = amount1):
并具体针对您的示例:
* 1如果你想知道为什么我选择c作为金额,因为php中的函数count() 将所有组合放在一起 我们现在如何得到阵列数量的所有组合,我们有? 我们循环遍历我们已经拥有的所有组合(从一个组合开始,一个“空组合”($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:不是数字 因此,正如您在上面的示例中所看到的,我们现在拥有了所有数组长度的所有组合. 但是为了只获得具有所需长度的组合,我们每次迭代都会覆盖结果数组,因此最后只有具有预期长度的组合在结果数组中. 码: <?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);
?>
输出: Array
(
[0] => Array
(
[0] => 1
[1] => 4
[2] => 7
)
//...
[7] => Array
(
[0] => 2
[1] => 5
[2] => 8
)
)
对于关联数组,您只需稍作修改,即: >首先使用array_keys()将数组键分配给变量,例如 $keys = array_keys($data); >使用第二个foreach循环中的键访问数据数组,意思是: foreach ($data[$count] as $v2) 至: foreach ($data[$keys[$count]] as $v2) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
