Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php动态嵌套循环帮助_Php_Dynamic_While Loop_Nested Loops - Fatal编程技术网

Php动态嵌套循环帮助

Php动态嵌套循环帮助,php,dynamic,while-loop,nested-loops,Php,Dynamic,While Loop,Nested Loops,我不知道该怎么做 我的代码比下面的代码长,但总结如下: $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

我不知道该怎么做

我的代码比下面的代码长,但总结如下:

$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++;
}
现在我的问题如下

如何根据$array中的元素数量动态创建嵌套到其他循环中的while循环

目前,您可以看到有4个元素(4个子数组),因此有4个while循环

注意,可以随意更改变量名


如果您能提供帮助,即使您只是给出一个链接,但最好给出完整的答案,也会非常感谢。

awnser是递归的

创建一个置换数组的函数,并在该函数中使用不带第一个元素的数组调用相同的函数。在这之后,您将排列第一个元素,并将其前置到前一个函数调用的结果

请确保具有良好的停止条件(如果使用空数组调用它,只需返回空数组),否则将出现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;
}

你能给我举个例子吗?这个函数的工作原理与我认为
$permtail
实际上没有被设置的事实不同。哦,如果已知循环数,则不要使用while循环。用于循环。或者foreach,如果数组计数隐式地知道循环数。我知道,这是一个旧脚本,如果我要重写它,我还没有时间修改它,它是多余的。你只想计算a*或所有字符的所有可能组合的排列吗,我推导出可能的组合是2^n,其中n是字母数。所以我需要这个脚本来为n的任何值生成所有可能的安排。此外,每个字母只能有一次,并且必须按a->z的顺序排列
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;
}