Symfony2 Doctrine迭代,而next()

 mthj1688 发布于 2023-02-09 11:16

我正在寻找一个有效的解决方案,在symfony2中迭代一个mongodb .不幸的是,这似乎不起作用?Symfony忽略了这个功能!PersistentCollectionnext()

while (($animal = $zooAnimals->next()) !== false) {

    $color = $animal->getColor();

    print_r($color); die; // Test and die
}

print_r('Where are the animals?'); die; // << Current result

参考:Doctrine\ODM\MongoDB\PersistentCollection

1 个回答
  • 这不是Symfony的"错误".这是对如何迭代对象的误解.有几种方法可以为您的用例处理此问题.这里有一些

    使用foreach!

    你的PersistentCollection工具Collection实现了IteratorAggregate哪些实现(长路嘿?). 实现接口的对象可以在语句中使用.Traversable
    Traversableforeach

    IteratorAggregate强迫你实现一个getIterator必须返回的方法Iterator.最后还实现了Traversable接口.

    使用迭代器

    Iterator interface强制你的对象声明5个方法,以供a使用 foreach

    class MyCollection implements Iterator
    {
        protected $parameters = array();
        protected $pointer = 0;
    
        public function add($parameter)
        {
            $this->parameters[] = $parameter;
        }
    
        /**
         * These methods are needed by Iterator
         */
        public function current()
        {
            return $this->parameters[$this->pointer];
        }
    
        public function key()
        {
            return $this->pointer;
        }
    
        public function next()
        {
            $this->pointer++;
        }
    
        public function rewind()
        {
            $this->pointer = 0;
        }
    
        public function valid()
        {
            return array_key_exists($this->pointer, $this->parameters);
        }
    }
    

    您可以使用任何实现Iterator它的类 -Demo file

    $coll = new MyCollection;
    $coll->add('foo');
    $coll->add('bar');
    
    foreach ($coll as $key => $parameter) {
        echo $key, ' => ', $parameter, PHP_EOL;
    }
    

    暂时使用迭代器

    为了 foreach 一样使用这个类.方法应该这样调用 - Demo file

    $coll->rewind();
    
    while ($coll->valid()) {
        echo $coll->key(), ' => ', $coll->current(), PHP_EOL;
        $coll->next();
    }
    

    2023-02-09 11:19 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有