php迭代器类是如何工作的?(遍历结束表行集)


How php iterator class works ? (Iterate through zend table row set)

我有一个包含100条记录的对象。我想遍历它并删除对象中的所有数据。

如何在PHP迭代器类中做到这一点?

(对象为ZEND表行集对象)

(此处delete表示我们只是将数据库中的delete_flag设置为1。数据不会从数据库中被物理地删除。

,

$zendTableRowSetObject->list[0]->delete_flag = 1
$zendTableRowSetObject->list[2]->delete_flag = 1
$zendTableRowSetObject->list[3]->delete_flag = 1
$zendTableRowSetObject->save(); 

->save()是Zend函数,它将更新用于调用此方法的对象。

(除了这个任何其他方法http://php.net/manual/en/language.oop5.iterations.php)

(不使用foreach循环是否有办法做到这一点?)

给我一些例子。

这是我的迭代器类
class PersonListIter implements Iterator
{
     protected $_PersonList;
    /**
     * Index of current entries
     * It's used for iterator
     * @var integer
     */
    protected $_entryIndex = 0;
    /**
     * Entries data sets
     * @var array
     */
    protected $_entries;
    /*
     * Initialization of data. 
     * 
     * @params  Zend_Db_Table_Rowset    $list   Row Object
     * @return  null
     */    
    public function __construct ( $list )
    {
        $this->_PersonList = $list;
        $this->_entryIndex = 0;
        $this->_entries = $list->getCount();
    }
    /*
     * Iterator interface method to rewind index
     * @return  null
     */     
    public function rewind()
    {
        $this->_entryIndex = 0;
    }
    /*
     * Iterator interface method to return Current entry
     * @return  Zend_Db_Table_Row   Current Entry
     */         
    public function current()
    {
        return $this->_PersonList->getElement($this->_entryIndex);
    }
    /*
     * Iterator interface method to return index of current entry
     * @return  int     Current Entry Index
     */     
    public function key()
    {
        return $this->_entryIndex;
    }
    /*
     * Iterator interface method to set the next index
     * @return  null
     */      
    public function next()
    {
        $this->_entryIndex += 1;
    }
    /*
     * Iterator interface method to validate the current index
     * @return  enum    0/1 
     */      
    public function valid()
    {
        return (0 <= $this->_entryIndex && $this->_entryIndex < $this->entries)?1:0;
    }
} // class PersonListIter

$zendTableRowSetObject是迭代器类中的PersonList对象

您不能一次删除它们,您必须遍历(使用foreach或while与next()结合使用)来删除它们。

在冲浪的时候,我发现了下面的链接,你可能会感兴趣。这很好地解释了PHP中实现迭代器模式的用法。>> http://www.fluffycat.com/PHP-Design-Patterns/Iterator/