达到的结果:

count: 5, level: 3
0_1_2
0_1_3
0_1_4
0_2_3
0_2_4
0_3_4
1_2_3
1_2_4
1_3_4
2_3_4

function actionTest($count, $level) {
        echo "count: {$count}, level: {$level}\n";
        foreach (new arrangeIterator($count, $level) as $k=>$v) {
            echo "{$k}\n";
        }
    }


class arrangeIterator implements Iterator {

    private $count, $level;
    private $idxArr = [];

    public function __construct($count, $level) {
        $this->count = $count;
        $this->level = $level;
        $this->idxArr = range(0, $this->level-1);
    }

    /**
     * Return the current element
     * @link  https://php.net/manual/en/iterator.current.php
     * @return mixed Can return any type.
     * @since 5.0.0
     */
    public function current() {
        // TODO: Implement current() method.
        return $this->idxArr;
    }

    /**
     * Move forward to next element
     * @link  https://php.net/manual/en/iterator.next.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function next() {
        // TODO: Implement next() method.
        $i = $this->level-1; //最大下标
        $n = 1;
        $idx = $i;
        while($i>=0) {
            if ($this->idxArr[$i] + 1 > $this->count-$n) {
                $i--;
                $n++;
                continue;
            }
            $idx = $i;
            break;
        }
        $tmp = $this->idxArr[$idx];
        $step = 1;
        for($i=$idx; $i<$this->level; $i++) {
            $this->idxArr[$i]=$tmp+$step;
            $step++;
        }

    }

    /**
     * Return the key of the current element
     * @link  https://php.net/manual/en/iterator.key.php
     * @return mixed scalar on success, or null on failure.
     * @since 5.0.0
     */
    public function key() {
        // TODO: Implement key() method.
        return implode('_', $this->idxArr);
    }

    /**
     * Checks if current position is valid
     * @link  https://php.net/manual/en/iterator.valid.php
     * @return bool The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     * @since 5.0.0
     */
    public function valid() {
        // TODO: Implement valid() method.
        return $this->level>0 && $this->idxArr[0] <= $this->count - $this->level && $this->idxArr[$this->level-1] <= $this->count - 1;
    }

    /**
     * Rewind the Iterator to the first element
     * @link  https://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function rewind() {
        // TODO: Implement rewind() method.
        $this->idxArr = range(0, $this->level-1);
    }
}

标签: php

添加新评论