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中是否有函数或任何可以执行此操作的算法?我不知道从哪里开始。你能帮助我吗 ?

我想将7个给定数字的所有组合(它们从数组中取出)放入5个插槽中,而无视顺序

回答:

如果链接断开,这里是代码。

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数组组合 的全部内容, 来源链接: utcz.com/qa/424439.html

回到顶部