Php,是否有一个迭代器转换器阵列?

时间:2016-05-27 14:20:03

标签: php

对于数组http://php.net/manual/en/function.iterator-to-array.php有迭代器是好的,但有什么可以反转的吗?

2 个答案:

答案 0 :(得分:2)

是的,如果颠倒意味着只是从给定的数组中创建一个迭代器

$array = array(
  'a' => 1,
  2 => new stdClass,
  3 => array('subArrayStuff'=>'value')
);

$iterator = new ArrayObject($array);

$arrayAgain = iterator_to_array($iterator);

试试吧。

http://php.net/manual/en/class.arrayobject.php

请同时阅读Difference between ArrayIterator, ArrayObject and Array in PHP

答案 1 :(得分:1)

http://php.net/manual/en/class.iterator.php以下是使用数组的MyIterator示例。您可以更改构造函数并传递任何数组

class myIterator implements Iterator {
    private $position = 0;
    private $array = array();  

    public function __construct($data = array()) {
        $this->array = $data;
        $this->position = 0;
    }

    function rewind() {
        var_dump(__METHOD__);
        $this->position = 0;
    }

    function current() {
        var_dump(__METHOD__);
        return $this->array[$this->position];
    }

    function key() {
        var_dump(__METHOD__);
        return $this->position;
    }

    function next() {
        var_dump(__METHOD__);
        ++$this->position;
    }

    function valid() {
        var_dump(__METHOD__);
        return isset($this->array[$this->position]);
    }
}