2012-01-06 6 views
0

多変量テストのレシピ作成に問題があります。たとえば、私が衣装の組み合わせを試したければ、私は3種類の帽子、シャツ、パンツを持っていました。私は重複することなくそれらのすべての可能な組み合わせをリストしたいと思います。これは、これまでの私の思考プロセスである:次にPHPで複数のバリエーションテストのレシピを作成するには?

// outfit #1 
$outfit[0][0] = "hat A "; 
$outfit[0][1] = "shirt A "; 
$outfit[0][2] = "pants A "; 

// outfit #2 
$outfit[0][0] = "hat B "; 
$outfit[0][1] = "shirt B "; 
$outfit[0][2] = "pants B "; 

// outfit #3 
$outfit[0][0] = "hat C "; 
$outfit[0][1] = "shirt C "; 
$outfit[0][2] = "pants C "; 

function recipeMaker() 
{ 
    $i = 0; 
    $j = 0; 
    foreach ($outfit as $outfit_2) 
    { 
      foreach ($outfit_2 as $outfit_3) 
      { 
       ...some magic here... 
       recipe[$i][$j] = ...something goes here... 
       $j++; 
      } 
    $i++; 
    }  
} 

foreach ($recipe as $r) 
{ 
    echo $r . "<br />"; 
} 

それを出力すべき:

hat A shirt A pants A 
hat B shirt A pants A 
hat C shirt A pants A 
hat A shirt B pants A 
etc. 

答えて

1

あなたが服を拡張したいときは、foreachループをネストのルートを下ることができますが、何が起こる(例:ネクタイのリストを追加する)ここでは、コレクションの任意の数から利用可能な組み合わせを出力ソリューションです:

class Combiner { 
    protected $_collections; 
    protected $_combinations; 

    public function __construct() { 
     $args = func_get_args(); 

     if (count(array_filter(array_map('is_array', $args))) !== func_num_args()) { 
      throw new Exception('Can only pass array arguments'); 
     } 

     $this->_collections = $args; 
    } 

    protected function _getBatch(array $batch, $index) { 
     if ($index < count($this->_collections)) { 
      foreach ($this->_collections[$index] as $element) { 
       // get combinations of subsequent collections 
       $this->_getBatch(array_merge($batch, array($element)), $index + 1); 
      } 
     } else { 
      // got a full combination 
      $this->_combinations[] = $batch; 
     } 
    } 

    public function getCombinations() { 
     if (null === $this->_combinations) { 
      $this->_getBatch(array(), 0); 
     } 

     return $this->_combinations; 
    } 
} 

$hats = array('Hat A', 'Hat B', 'Hat C'); 
$shirts = array('Shirt A', 'Shirt B', 'Shirt C'); 
$pants = array('Pants A', 'Pants B', 'Pants C'); 

$combiner = new Combiner($hats, $shirts, $pants); 
var_dump($combiner->getCombinations()); 

それはタイプのリストに沿って移動し、1を選び、その後再帰的に行くタイプの残りの組み合わせを構築する(ハットAと言います)その項目。新しい型を追加するには、別の引数をコンストラクタに渡すだけで簡単です。

0

まず、これは得るためにあなたの同様のコンテンツへのアレイ(1つの配列のすなわち、すべての帽子、別などのすべてのシャツを)アレンジ:

$hats[0] = 'Hat A'; 
$hats[1] = 'Hat B'; 
$hats[2] = 'Hat C'; 

$shirts[0] = 'Shirt A'; 
$shirts[1] = 'Shirt B'; 
$shirts[2] = 'Shirt C'; 

$pants[0] = 'Pants A'; 
$pants[1] = 'Pants B'; 
$pants[2] = 'Pants C'; 

$recipe = array(); 

が続いてforeachのはそうのような各要素をループするために構築し使用します。

foreach ($hats as $hat) { 
    foreach ($shirts as $shirt) { 
     foreach ($pants as $pant) { 
      $recipe = $hat." ".$shirt." ".$pant; 
     } 
    } 
} 

foreach ($recipe as $r) { 
    echo $r."<br>"; 
} 
関連する問題