2

Okay, here I have a multidimensional array. It consists of 3 arrays each with 3 numbers.

$numbers = array(
    array("1", "2", "3"),
    array("4", "5", "6"),
    array("7", "8", "9"),
);

I want to generate and list every possible combination of the numbers from these arrays. So for example, "147" (1 being from the first array, 4 being from the second array and 7 being from the third array), "247, 347, 157, 257, 357, 167, 267, 367, etc..."

The important thing is that the first number must come from the first array, the second number from the second array and the third from the third array.

I have tried to loop through these arrays using nested foreach loops, but I can't quite figure it out and it's making my head spin. Hope that makes sense, any help would be greatly appreciated.

Dannyd86
  • 87
  • 3
  • 14
  • possible dup of http://stackoverflow.com/questions/4549794/how-to-find-every-possible-combination-of-arrays-in-php – Crisp Feb 26 '13 at 23:44

2 Answers2

3
$numbers = array(
    array("1", "2", "3"),
    array("4", "5", "6"),
    array("7", "8", "9"),
);

$f_nb = $numbers['0'];
$s_nb = $numbers['1'];
$t_nb = $numbers['2'];

$final_array = array();

for($a = 0; $a<sizeof($f_nb); $a++) 
{
    for($b = 0; $b<sizeof($s_nb); $b++) 
    {
        for($c = 0; $c<sizeof($t_nb); $c++) 
        {
            $final_array[] = $f_nb["$a"] . $s_nb["$b"] . $t_nb["$c"];
        }
    }
}

print_r($final_array);
S.B.
  • 161
  • 1
  • 8
2
<?php
$numbers = array(
    array("1", "2", "3"),
    array("4", "5", "6"),
    array("7", "8", "9"),
);

for ($i=0;$i<3;$i++) {
  for ($j=0;$j<3;$j++) {
    for ($k=0;$k<3;$k++) {
      echo $numbers[0][$i]+" "+$numbers[1][$j]+" "+$numbers[2][$k]+"\n";
    }
  }
}
?>

I didn't program in php before so the code may make your eyes bleed. Nonetheless, the code works and demonstrates the idea.

Terry Li
  • 16,870
  • 30
  • 89
  • 134