这是一个数组。
$item = array('A', 'B', 'C', 'D');
我想要列出这个数组中所有可能的订单,例如:
A
A,B
A,B,C
A,B,C,D
A,C
A,C,D
A,C,B
...
B,A
B,A,C
....
我该如何做到这一点?
这是一个数组。
$item = array('A', 'B', 'C', 'D');
你可以使用这个递归函数:
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;
};
}
$perms = recursive_permutations(array('A', 'B', 'C', 'D'));
echo '<pre>' . print_r($perms, true) . '</pre>';
php
没有什么特别的。它是一个通用算法。你只需要知道这个算法。如果你展示出你到目前为止编写的代码,你可以说 "在 php 中"。 - footy