我需要帮助循环一个简单的数组,并找到其元素的所有可能组合,如下所示:
array('a', 'b', 'c');
预期结果是:
array(
0=>array('a', 'a', 'a'),
1=> array('a', 'a', 'b')
);
我完全失去了,非常感谢任何帮助或指示!
这是我到目前为止所拥有的。
$array = array('red', 'blue', 'green', 'white');
$count = count($array);
$current = array_fill(0, $count, $array[0]);
$last = array_fill(0, $count, end($array));
$output = array();
$i = 0;
while ($current != $last) {
$indexes = str_pad($i, $count, "0", STR_PAD_LEFT);
$j = str_split($indexes);
foreach ($j as $a => $b) {
if (isset($array[$b])) {
$output[$i][] = $array[$b];
}
}
$current = $output[$i];
$i++;
}
// cleaver duplication removal
$result = array_map("unserialize", array_unique(array_map("serialize", $output)));
echo '<pre>';
print_r($result);
echo '</pre>';
重复删除代码来自here。
答案 0 :(得分:1)
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);
}
}
}