2016-02-23 77 views
1

我有五個數組,我需要生成所有的可能性。爲了簡單起見,讓我有三個演示:如何從多個數組中獲得所有可能性?

$material = array("cotton","polyester"); 
$size = array("small", "medium", "large"); 
$color = array("blue", "red", "green", "black"); 

我要拿出一個包含所有可能性多維數組:

cotton, small, blue 
cotton, small, red 
cotton, small, green 
cotton, small, black 
cotton, medium, blue 
cotton, medium, red 
cotton, medium, green 
cotton, medium, black 
cotton, large, blue 
cotton, large, red 
cotton, large, green 
cotton, large, black 
polyester, small, blue 
polyester, small, red 
polyester, small, green 
polyester, small, black 
polyester, medium, blue 
polyester, medium, red 
polyester, medium, green 
polyester, medium, black 
polyester, large, blue 
polyester, large, red 
polyester, large, green 
polyester, large, black 

我會怎麼做呢?

+0

你想要一個笛卡爾乘積。這個鏈接有一個通用的方法,可以處理任何數量的項目。 http://stackoverflow.com/questions/2516599/php-2d-array-output-all-combinations –

回答

0

試試這個。

$combinations = array(); 
foreach ($material as $value1) { 
    foreach ($size as $value2) { 
     foreach ($color as $value3) { 
      combinations[] = array($value1,$value2,$value3); 
     } 
    } 
} 
0

這個工作對我來說

$material = array("cotton","polyester"); 
    $size = array("small", "medium", "large"); 
    $color = array("blue", "red", "green", "black"); 

    foreach ($material as $a) { 

     foreach ($size as $b) { 

      foreach ($color as $c) { 

       $test = $a. ','. $b. ','.$c; 
      } 
     } 
    } 
相關問題