如何从多个数组生成固定大小的组合?

时间:2016-05-20 01:18:39

标签: php arrays combinations

我需要找到具有固定子集大小的多个数组中的所有项目组合。例如,我有3个数组:

$A = array('A1','A2','A3');
$B = array('B1','B2','B3');
$C = array('C1','C2','C3');

我想从上面的数组生成大小为2的组合。像:

$Combinations = array(
    [0] => array('A1', 'B1'),
    [1] => array('A1', 'C1'),
    [2] => array('A2', 'B1'),
    [3] => array('A2', 'C1')
);

solution生成所有组合,但似乎没有大小参数。

寻求帮助!

2 个答案:

答案 0 :(得分:0)

$A = array('A1','A2','A3');
$B = array('B1','B2','B3');
$C = array('C1','C2','C3');
$All = array();
 foreach ($A as $key1=>$value1){
 foreach ($B as $key2=>$value2){
     $All[] = array($value1,$value2 );
 }
 foreach ($C as $key3=>$value3){
     $All[] = array($value1,$value3 );
 }
 }

 print_r($All);

在此处检查输出:https://eval.in/574060

答案 1 :(得分:0)

最后,找到了解决方案。使用以下脚本,您可以将任意数量的数组与每个组合的任意数量的元素组合在一起。请阅读代码中的注释,并尝试了解会发生什么。

<?php
$A = array('A1', 'A2', 'A3');
$B = array('B1', 'B2', 'B3');
$C = array('C1', 'C2', 'C3');

$combinationCount = 5;
$itemsPerCombination = 2;
$array = ['A', 'B', 'C'];

$combinations = array();
for ($x = 0; $x < $combinationCount; $x++) {
    //to keep temporary names of arrays which come in a combination
    $arrays = array();
    for ($y = 0; $y < $itemsPerCombination; $y++) {
        $valid = false;
        while (!$valid) {
            //get a random array, check if it is already in our selection
            $arrayElement = $array[rand(0, count($array) - 1)];
            if (in_array($arrayElement, $arrays)) {
                $valid = false;
                continue;
            }
            $arrays[] = $arrayElement;
            $valid = true;
        }
    }

    $found = false;
    while (!$found) {
        //for each selection in our selected arrays, take a random element and add to the combination.
        $combination = array();
        foreach ($arrays as $arr) {
            $temp=$$arr;
            $combination[] = $temp[rand(0, count($temp) - 1)];
        }
        if (in_array($combination, $combinations)) {
            $found = false;
            continue;
        }
        $combinations[] = $combination;
        $found = true;
    }
}
echo(json_encode($combinations));
?>