PHP数组组合

我有7个数字(1,2,3,4,5,6,7)的数组,我想要做成5个数字对(1,2,3,4,5),(1,2,3 ,4,6,),(1,2,3,4,7)。 (1,2,3,4,5)等于(4,5,3,1,2)

我想知道是否有一个函数在PHP或任何algorithm可以做到这一点? 我不知道从哪里开始。 你可以帮我吗 ?

我想把7个给定数字(它们从一个数组中取出)的所有组合放到5个插槽中,不pipe顺序如何

你可以使用http://stereofrog.com/blok/on/070910find的解决scheme。;

Incase链接下来这里的代码….

class Combinations implements Iterator { protected $c = null; protected $s = null; protected $n = 0; protected $k = 0; protected $pos = 0; function __construct($s, $k) { if(is_array($s)) { $this->s = array_values($s); $this->n = count($this->s); } else { $this->s = (string) $s; $this->n = strlen($this->s); } $this->k = $k; $this->rewind(); } function key() { return $this->pos; } function current() { $r = array(); for($i = 0; $i < $this->k; $i++) $r[] = $this->s[$this->c[$i]]; return is_array($this->s) ? $r : implode('', $r); } function next() { if($this->_next()) $this->pos++; else $this->pos = -1; } function rewind() { $this->c = range(0, $this->k); $this->pos = 0; } function valid() { return $this->pos >= 0; } protected function _next() { $i = $this->k - 1; while ($i >= 0 && $this->c[$i] == $this->n - $this->k + $i) $i--; if($i < 0) return false; $this->c[$i]++; while($i++ < $this->k - 1) $this->c[$i] = $this->c[$i - 1] + 1; return true; } } foreach(new Combinations("1234567", 5) as $substring) echo $substring, ' '; 

12345 12346 12347 12356 12357 12367 12456 12457 12467 12567 13456 13457 13467 13567 14567 23456 23457 23467 23567 24567 34567

 <?php echo "<pre>"; $test = array("test_1","test_2","test_3"); // Get Combination $return = uniqueCombination($test); //Sort sort($return); //Pretty Print print_r(array_map(function($v){ return implode(",", $v); }, $return)); function uniqueCombination($in, $minLength = 1, $max = 2000) { $count = count($in); $members = pow(2, $count); $return = array(); for($i = 0; $i < $members; $i ++) { $b = sprintf("%0" . $count . "b", $i); $out = array(); for($j = 0; $j < $count; $j ++) { $b{$j} == '1' and $out[] = $in[$j]; } count($out) >= $minLength && count($out) <= $max and $return[] = $out; } return $return; } ?> 

产量

 Array ( [0] => test_1 [1] => test_2 [2] => test_3 [3] => test_1,test_2 [4] => test_1,test_3 [5] => test_2,test_3 [6] => test_1,test_2,test_3 ) 

PEAR存储库中的Math_Combinatorics完全符合您的要求:

返回给定集合和子集大小的所有组合和排列的程序包,无需重新sorting。 关联数组被保存。

 require_once 'Math/Combinatorics.php'; $combinatorics = new Math_Combinatorics; $input = array(1, 2, 3, 4, 5, 6, 7); $output = $combinatorics->combinations($input, 5); // 5 is the subset size // 1,2,3,4,5 // 1,2,3,4,6 // 1,2,3,4,7 // 1,2,3,5,6 // 1,2,3,5,7 // 1,2,3,6,7 // 1,2,4,5,6 // 1,2,4,5,7 // 1,2,4,6,7 // 1,2,5,6,7 // 1,3,4,5,6 // 1,3,4,5,7 // 1,3,4,6,7 // 1,3,5,6,7 // 1,4,5,6,7 // 2,3,4,5,6 // 2,3,4,5,7 // 2,3,4,6,7 // 2,3,5,6,7 // 2,4,5,6,7 // 3,4,5,6,7 

在这里我举了一个例子如何做到这一点https://stackoverflow.com/a/8880362/1010916

你应该从上面的链接执行以下function:

 getCombinations(array(1,2,3,4,5,6,7),5) 

尝试这里解释的实现之一

algorithm从n返回所有k个元素的组合