2016-05-20 6 views
-1

固定サブセットサイズのいくつかの配列でアイテムのすべての組み合わせを見つける必要があります。たとえば、私は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は、すべての組み合わせを生成しているが、それにサイズパラメータを持っていないようです。

助けを探しています!ここ

+0

1つのループの内側に2つのループを試してください。 – C2486

+0

@リシ:もっと詳しく教えてもらえますか? –

+0

解決策を与えました – C2486

答えて

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

+0

あなたはこのようにしたいと思っていますか? – C2486

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)); 
?> 
関連する問題