php动态嵌套循环帮助

| 我不知道该如何处理。 我的代码比以下代码长,但这是对它的总结:
$array = array(array(\'A\',\'a\'),array(\'B\',\'b\'),array(\'C\',\'c\'),array(\'D\',\'d\'));
$array2 = array();
$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++;
}
好的,因此,结果$ array2将如下所示:
array ( 
    0 => \'ABCD\',
    1 => \'ABCd\', 
    2 => \'ABcD\', 
    3 => \'ABcd\', 
    4 => \'AbCD\',
    ........ // i have omitted several almost identical lines
    14 => \'abcD\', 
    15 => \'abcd\',
)
现在我的问题如下。 我如何基于$ array中有多少个元素动态地创建一个while循环嵌套到其他循环中? 如您所见,目前有4个元素(4个子数组),因此有4个while循环。 注意,随时更改变量名。 如果您能提供帮助,即使您只提供链接,也要感谢您,但最好提供完整的答案。     
已邀请:
篷车是递归的。 创建一个对数组进行排列的函数,然后在该函数中使用不带第一个元素的数组调用同一函数。之后,对第一个元素进行置换,并将其放在前一个函数调用的结果之前。 确保具有良好的停止条件(如果使用空数组调用该条件,则只需返回一个空数组),否则您将得到stackoverflow或索引超出范围错误。 我的php有点生锈,我不确定是否可以编译,但是看起来应该像这样:
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;
}
    

要回复问题请先登录注册