PHP中数组的置换
我使用以下代码获取PHP中数组的所有排列:PHP中数组的置换,php,permutation,Php,Permutation,我使用以下代码获取PHP中数组的所有排列: $list = array(); function recursive_permutations($items,$perms = array( )) { static $list; if (empty($items)) { $list[] = join(',', $perms); } else { for ($i = count($items)-1;$i>=0;--$i) { $newitems = $items; $n
$list = array();
function recursive_permutations($items,$perms = array( ))
{
static $list;
if (empty($items)) {
$list[] = join(',', $perms);
} else {
for ($i = count($items)-1;$i>=0;--$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
recursive_permutations($newitems, $newperms);
};
return $list;
};
}
// FIRST RUN
$perms = recursive_permutations(range(1,3));
echo '<pre>' . print_r($perms, true) . '</pre>';
// SECOND RUN
$perms = recursive_permutations(range(4,6));
echo '<pre>' . print_r($perms, true) . '</pre>';
如果我只执行一次函数,它就可以正常工作。但是,如果需要对第二个数组重复此过程,则会将结果添加到第一个结果中
如何在第一次运行后清除结果?或者a清除非递归调用上的静态,b不使用静态,然后将前向迭代返回的数组合并到当前已知列表中。e、 g.$list=数组\u合并$list,递归\u置换。。。没有测试。
function recursive_permutations($items, $perms = [])
{
$list = [];
if (empty($items)) {
$list[] = join(',', $perms);
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$list = array_merge($list, recursive_permutations($newitems, $newperms));
};
};
return $list;
}
// FIRST RUN
$perms = recursive_permutations(range(1, 3));
echo '<pre>' . print_r($perms, true) . '</pre>';
// SECOND RUN
$perms2 = recursive_permutations(range(4, 6));
echo '<pre>' . print_r($perms2, true) . '</pre>';