2011-07-15 27 views
0

我有包含100条记录的对象。我想遍历它并删除对象中的所有数据。php迭代器类如何工作? (通过zend表行集迭代)

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

(对象是使用Zend表行集对象)

(这里删除手段,我们仅仅做delete_flag在数据库中。数据不会从数据库中物理删除。)

例如:

$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对象

+1

如果要删除对象中的所有数据,为什么不直接删除对象呢? –

+0

(这里的删除表示我们只是将数据库中的'delete_flag'设为1.数据不会从数据库中物理删除。) – Sahal

+0

为什么foreach不好? – Marcin

回答

1

您不能删除所有这些一次,你必须通过(使用的foreach或同时进行迭代与next())一起删除它们。

冲浪时我找到了以下可能会对你感兴趣的链接。这解释了在PHP中使用实现迭代器模式的好方法。 >>http://www.fluffycat.com/PHP-Design-Patterns/Iterator/