2017-08-06 65 views
3

我构建了两个版本的PHP 7函数,它接受一个数组,并返回显示原始数组成员的所有排列的数组列表。例如,对于输入[1,2,3],期望的输出将是1,2和3的全部六个排列。PHP:为什么这些输出不同的结果?

我期望这两个版本的函数给出相同的输出,但是不知道为什么它们没有。这是第一个(按预期工作):

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]]

为什么会出现差异?

+0

问题是关于变量“$ selected”包含第一个for循环的第一次迭代的结果,它需要在清空之前清除进入循环的下一次迭代。添加行“$ selected = array();”在endforeach语句之前将使代码工作。 –

回答

2

问题是关于变量“$ selected”持有for循环的第一次迭代的结果,并且在进入下一次迭代循环之前需要重新初始化。在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']); 
+0

刚刚使用更多类型的输入值进行测试 - 如果输入数组大小超过2,清除功能也无济于事。检查是否有任何简单的方法可以解决此问题,而不是第一个版本的功能。 –

相关问题