从 PHP 5.5 开始,您可以使用生成器。生成器节省大量内存并且速度更快(与pc_permute()相比,一半以上)。因此,如果您有机会安装PHP 5.5,那么您肯定需要Generators。这个截图是从Python移植过来的:https://stackoverflow.com/a/104436/3745311
function permutations(array $elements)
{
if (count($elements) <= 1) {
yield $elements;
} else {
foreach (permutations(array_slice($elements, 1)) as $permutation) {
foreach (range(0, count($elements) - 1) as $i) {
yield array_merge(
array_slice($permutation, 0, $i),
[$elements[0]],
array_slice($permutation, $i)
);
}
}
}
}
示例用法:
$list = ['a', 'b', 'c'];
foreach (permutations($list) as $permutation) {
echo implode(',', $permutation) . PHP_EOL;
}
输出:
a,b,c
b,a,c
b,c,a
a,c,b
c,a,b
c,b,a