【问题标题】:Permutations of array in PHPPHP中数组的排列
【发布时间】:2026-01-09 09:30:01
【问题描述】:

我正在使用以下代码 (https://www.hashbangcode.com/article/getting-all-permutations-array-php) 在 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;
   $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) 不使用静态,并将前向迭代返回的数组合并到当前已知列表中。例如$list = array_merge($list, recursive_permutations(...))(未测试)。

标签: php permutation


【解决方案1】:
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>';

【讨论】: