2013-06-06 95 views
3

如何在PHP如何在PHP中從字符串創建可能的字符串組合?

精通創建串串的可能的組合:

input = 'abc'; 
output = array(
    [0]=> "a" 
    [1]=> "ab" 
    [2]=> "abc" 
    [3]=> "ac" 
    [4]=> "acb" 
    [5]=> "b" 
    [6]=> "ba" 
    [7]=> "bac" 
    [8]=> "bc" 
    [9]=> "bca" 
    [10]=> "c" 
    [11]=> "ca" 
    [12]=> "cab" 
    [13]=> "cb" 
    [14]=> "cba" 
) 

請幫幫忙,謝謝

+0

可能重複(http://stackoverflow.com/questions/12160843/generate-all-possible-combinations-使用-A-設定的串) – Rikesh

回答

1

轉換串字符數組,通過創建兩個循環創造一切可能的組合。

示例:此代碼完美(測試)。

<?PHP 
    function create_possible_arrays(&$set, &$results) 
    { 
     for ($i = 0; $i < count($set); $i++) 
     { 
      $results[] = $set[$i]; 
      $tempset = $set; 
      array_splice($tempset, $i, 1); 
      $tempresults = array(); 
      create_possible_arrays($tempset, $tempresults); 
      foreach ($tempresults as $res) 
      { 
       $results[] = $set[$i] . $res; 
      } 
     } 
    } 

    $results = array(); 
    $str = 'abc'; //your string 
    $str = str_split($str); //converted to array 
    create_possible_arrays($str, $results); 
    print_r($results); //displaying all results 
    ?> 
1

法西爾KK的代碼可能會遇到一個「最大函數嵌套層次」致命錯誤,

如果你有這個問題,試試這個:

$letters = str_split("abc"); 

$combos = $letters; 
$lastres = $letters; 
for ($i = 1; $i < count($letters); $i++) { 
    $newres = array(); 
    foreach ($lastres as $r) { 
     foreach ($letters as $let) { 
      $newres[] = $r . $let; 
     } 
    } 

    foreach ($newres as $w) { 
     $combos[] = $w; 
    } 

    $lastres = $newres; 
} 

print_r($combos); 

,那麼你只需要擔心關於內存:)

0

我很喜歡Axxe(謝謝),但你必須從組合數組中刪除重複值。

我提出這個功能:的[生成使用一組字符串的所有可能的組合]

function create_possible_arrays($string) { 
    $letters = str_split($string); 

    $combos = array_unique($letters); 
    $lastres = $letters; 
    for ($i = 1; $i < count($letters); $i++) { 
     $newres = array(); 
     foreach ($lastres as $r) { 
      foreach ($letters as $let) { 
       $new = $r . $let; 
       if (!in_array($new, $newres)) { 
        $newres[] = $new; 

        // Action 
        $combos[] = $new; 
       } 

      } 
     } 

     $lastres = $newres; 

    } 

    return $combos; 
} 
相關問題