你正在寻找排列公式:
nPk = n!/(n-k)!
在你的情况下,你有9个条目,你想选择所有的,9P9 = 9! = 362880
你可以找到一个PHP算法排列在O’Reilly的“PHP Cookbook”的食谱4.26中。
pc_permute(array(0, 1, 2, 3, 4, 5, 7, 8));
从O’Reilly复制:
function pc_permute($items, $perms = array( )) {
if (empty($items)) {
print join(' ', $perms) . "\n";
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
pc_permute($newitems, $newperms);
}
}
}