1

I have five arrays that I need to generate all the possibilities for. For simplicity purposes, let me demonstrate with three:

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

I want to come up with a multidimensional array that contains all possibilities:

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

How would I do this?

j08691
  • 204,283
  • 31
  • 260
  • 272
MultiDev
  • 10,389
  • 24
  • 81
  • 148
  • You are wanting a cartesian product. This link has a general purpose method that can handle any number of items. http://stackoverflow.com/questions/2516599/php-2d-array-output-all-combinations – John McKnight Feb 23 '16 at 03:18

2 Answers2

0

Try this.

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

this worked for me

    $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;
            }
        }
    }
prats1411
  • 162
  • 12