我有这段代码:
<?php
$str = "apple pear banana orange";
$str_splode = explode(' ',$str);
$combos = showCombo(array(), $str_splode);
foreach($combos as $key=>$array){
echo $key.PHP_EOL;
displayArrayByKey($key, $array);
}
function displayArrayByKey($str, $arr){
foreach($arr as $key=>$array){
$string = $str. " " . $key;
echo $string . PHP_EOL;
if(count($array)> 0){
displayArrayByKey($string, $array);
}
}
}
function showCombo($str_arr, $arr){
$ret = array();
foreach($arr as $val){
if(!in_array($val, $str_arr)){
$temp = $str_arr;
$temp[] = $val;
$ret[$val] = showCombo($temp, $arr);
}
}
return $ret;
}
?>
它打印$ str var中的每个单词组合。 问题是我只想打印n个单词的组合(其中n是我的$ str var中的单词数,在这种情况下:4)。我怎样才能做到这一点?
答案 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);
}
}
}
pc_permute(explode(" ", "apple pear banana orange"));