开发者

Php dynamic nest loops help

I have no idea how to approach this.

My code is longer than the following but this about sums it up:

$array = array(array('A','a'),array('B','b'),array('C','c'),array('D','d'));
$array2 = arr开发者_C百科ay();
$i = 0;
while ($i < 2) {
    $j = 0;
    while ($j < 2) {
        $k = 0;
        while ($k < 2) {
            $l = 0;
            while ($l < 2) {
                $array2[] = $array[0][$i] . $array[1][$j] . $array[2][$k] . $array[3][$l];
                $l++;
            }
            $k++;
        }
        $j++;
    }
    $i++;
}

Okay so what the resultant $array2 will look like is:

array ( 
    0 => 'ABCD',
    1 => 'ABCd', 
    2 => 'ABcD', 
    3 => 'ABcd', 
    4 => 'AbCD',
    ........ // i have omitted several almost identical lines
    14 => 'abcD', 
    15 => 'abcd',
)

Now my question is as follows.

How would i dynamically create a while loop nested into the others based on how many elements are in $array?

At the moment as you can see there is 4 elements (4 sub arrays) and hence 4 while loops.

Note, feel free to change variable names.

Thanks heaps if you can help, even if you just give a link but a full answer is preferred.


The awnser is recursion.

Create a function that permutates the array and in that function you call the same function with the array without the first element. After that you permutate the first element and prepend it to the result of the former function call.

Be sure to have a good stop condition (if it is called with an empty array, just return an empty array) otherwise you will get a stackoverflow or an index out of bounds error.


My php is a little rusty and I'm not sure if this compiles, but it should look a lot like this:

function permutate($array) {
  if (empty($array)) {
    //Stop condition. 
    return $array;
  }
  //recursion
  $permtail = permutate(array_slice($array,1));
  //permtail now contains the permutated result of the array without 
  //the first element

  $result = array();
  //permutate the first element
  foreach($array[0] as $value) {
    //prepend it to all permutations
    foreach($permtail as $tail) {
      $result[] = array_merge((array)$value, $tail);
    }
  }
  return $result;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜