-1

I need to find all combinations of items in several arrays with fixed subset size. For example, I have the 3 arrays :

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

I want to generate combinations of size 2 from the above arrays. Like:

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

This solution is generating all combinations, but does not seem to have size parameter in it.

Looking for help!

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Vinay Modi
  • 347
  • 3
  • 7

2 Answers2

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);

Check output here : https://eval.in/574060

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
0

Finally, found a solution. With the following script, you can combine any number of arrays with any number of elements per a combination. Please read the comments in the code and try to understand what happens.

<?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));
?>
Imesha Sudasingha
  • 3,462
  • 1
  • 23
  • 34