2014-02-06 55 views
2

我有這樣的代碼:組合的n個字

<?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變量中的單詞數,在這種情況下爲4)。我怎樣才能做到這一點?

回答

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")); 

找到在:http://docstore.mik.ua/orelly/webprog/pcook/ch04_26.htm

+0

工作非常感謝! –