2016-01-18 8 views
-5

У меня есть массив со следующих значениямиПолучение всех возможных комбинаций массива

$in = array("A","B","C","D","E"); 

Я хочу, чтобы получить все возможные комбинации, указанных (п) нет.

например, если п = 2, возвращение АВ, AC, AD, AE, BC, BD, BE, CD, CE, DE

Если N = 3, возвращают ABC, ABD, ABE, BCD, BCE, CDE

Пожалуйста, как я могу достичь этого в PHP?

+1

Можете ли вы показать, что вы пытались и добились? Также почему Javascript и jQuery отмечены? – Rajesh

+2

Существует множество решений для данного задания на домашнюю работу, если вы исследуете использование Google. –

+1

Проверьте этот ответ http://stackoverflow.com/questions/19067556/php-algorithm-to-generate-all-combinations-of-a-specific-size-from-a-single-set – DanieleO

ответ

0
function sampling($chars, $size, $combinations = array()) { 

    # if it's the first iteration, the first set 
    # of combinations is the same as the set of characters 
    if (empty($combinations)) { 
    $combinations = $chars; 
    } 

    # we're done if we're at size 1 
    if ($size == 1) { 
    return $combinations; 
    } 

    # initialise array to put new values in 
    $new_combinations = array(); 

    # loop through existing combinations and character set to create strings 
    foreach ($combinations as $combination) { 
    foreach ($chars as $char) { 
     $new_combinations[] = $combination . $char; 
    } 
    } 

    # call same function again for the next iteration 
    return sampling($chars, $size - 1, $new_combinations); 

} 

// example 
$chars = array('a', 'b', 'c'); 
$output = sampling($chars, 2); 
var_dump($output); 

Подробнее об этом here

Смежные вопросы