PHP:为什么这些输出不同的结果?

PHP: why do these output different results?

我构建了两个版本的 PHP 7 函数,它接受一个数组,returns 一个数组列表,显示原始数组成员的所有排列。例如,对于输入 [1,2,3],预期输出将是 1、2 和 3 的所有六种排列。

我希望该函数的两个版本都能提供相同的输出,但无法弄清楚为什么它们不能。这是第一个(按预期工作):

function permutations(array $input): array {
  $func = function (array $selected, array $chooseFrom, array &$results) 
             use (&$func) {

    foreach ($chooseFrom as $k => $unchosen):
      $selectedCopy = $selected; // make a copy
      $chooseFromCopy = $chooseFrom; // make a copy

      $selectedCopy[] = $unchosen; // add the next unchosen item to selected list
      array_splice($chooseFromCopy, $k,1); // remove the item from chooseFrom list
      $func($selectedCopy, $chooseFromCopy, $results); // recursive call
    endforeach;

    // If we've used all items. Add selection to results
    if (empty($chooseFrom)) $results[] = $selected;
  };

  $results = [];
  $func([], $input, $results);
  return $results;
}

当我调用 permutations([1,2]) 时,我得到了预期的结果:[[1,2],[2,1]]

这是函数的非工作版本。唯一的区别在于 foreach:

function permutations2(array $input): array {

  $func = function (array $selected, array $chooseFrom, array &$results) 
             use (&$func) {

    foreach ($chooseFrom as $k => $unchosen):    
      $chooseFromCopy = $chooseFrom; // make a copy

      $selected[] = $unchosen; // add the next unchosen to the selected list
      array_splice($chooseFromCopy, $k, 1); // remove the item from chooseFrom list
      $func($selected, $chooseFromCopy, $results); // recursive call
    endforeach;

    // If we've used all items. Add selection to results
    if (empty($chooseFrom)) $results[] = $selected;
  };

  $results = [];
  $func([], $input, $results);
  return $results;
}

当我调用 permutations2([1,2]) 时,我得到了一个错误的结果:[[1,2],[1,2,1]]

为什么有区别??

问题出在保存 for 循环第一次迭代结果的变量“$selected”,它需要在进入下一次循环迭代之前重新初始化。在 for 循环之前将“$selected”存储在另一个变量(假设为 $tempselected)中,并在 endforeach 语句之前使用 $tempselected 重新初始化“$selected”变量将使代码正常工作。但是这个变化几乎与函数的工作示例相同:)

<?php

function permutations2(array $input): array {

  $func = function (array $selected, array $chooseFrom, array &$results) 
             use (&$func) {
    $selectedTemp = $selected;

    foreach ($chooseFrom as $k => $unchosen):    
      $chooseFromCopy = $chooseFrom; // make a copy

      $selected[] = $unchosen; // add the next unchosen to the selected list
      array_splice($chooseFromCopy, $k, 1); // remove the item from chooseFrom list
      $func($selected, $chooseFromCopy, $results); // recursive call
      $selected = $selectedTemp;
    endforeach;

    echo("<br>After For Loop <br>");
    // If we've used all items. Add selection to results
      if (empty($chooseFrom))  { $results[] = $selected;  }  
  };

  $results = [];
  $func([], $input, $results);
  return $results;
}
$res = permutations2(['a','b','c']);