php求一维数组的排列

<?php
class CombinationsGenerator
{
    public function generate(array $list)
    {
        if (count($list) > 2) {
            for ($i = 0; $i < count($list); $i++) {
                $listCopy = $list;

                $entry = array_splice($listCopy, $i, 1);
                foreach ($this->generate($listCopy) as $combination) {
                    yield array_merge($entry, $combination);
                }
            }
        } elseif (count($list) > 0) {
            yield $list;

            if (count($list) > 1) {
                yield array_reverse($list);
            }
        }
    }
}

$generator = new CombinationsGenerator();

$temp = [];
foreach ($generator->generate([1, 2, 3, 5, 5]) as $combination) {
    if (!in_array($combination, $temp))
        $temp[] = $combination;
//    var_dump($combination);
}
var_dump(count($temp));

$temp1 = [];
foreach ($generator->generate([1, 2, 3, 3]) as $combination) {
    if (!in_array($combination, $temp1)) $temp1[] = $combination;
}
var_dump(count($temp1));

  

上面的!in_array条件是去重

原文地址:https://www.cnblogs.com/eleven24/p/7380131.html