迭代器到数组
DatePeriod 是一个用于处理重复日期的 PHP 类。它的方法数量非常有限。因此,当我想使用重复日期执行基本数组函数时,我必须使用 iterator_to_array 将其复制到数组中
。奇怪的是,复制它似乎会破坏它。有什么想法吗?
$p=new DatePeriod(date_create('2008-01-01'),
DateInterval::createFromDateString( "+2 days" ),
date_create('2008-12-31'));
echo count(iterator_to_array($p)); //183
$a=iterator_to_array($p);
echo count($a); //0
DatePeriod is a PHP class for handling recurring dates. It has a very limited number of methods. So when I want to do basic array functions with the recurring dates, I have to copy it to an array with iterator_to_array
. Strangely, copying it seems to clobber it. Any ideas why?
$p=new DatePeriod(date_create('2008-01-01'),
DateInterval::createFromDateString( "+2 days" ),
date_create('2008-12-31'));
echo count(iterator_to_array($p)); //183
$a=iterator_to_array($p);
echo count($a); //0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是我要做的。我将扩展
DatePeriod
并实现toArray
方法:Here's what I'd do. I'd extend
DatePeriod
and implement atoArray
method:我想知道迭代器是否没有被 iterator_to_array() 重新缠绕,因此第二个调用开始以光标结尾进行迭代。您可以尝试以下操作:
如果迭代器不可回滚,您可以尝试在遍历对象之前克隆该对象,例如
I wonder if maybe the iterator isn't being re-wound by iterator_to_array(), so the second call starts iterating with the cursor at the end. You could try this:
If the iterator is not rewindable, you could try cloning the object before you traverse it, e.g.
据推测,第一次调用会遍历迭代器中的所有元素(即调用 next() 直到 valid() 为 false)。明智的行为是 iterator_to_array 从迭代器中的当前位置开始转换 - 让其静默倒回将是不灵活的,并且可能会引发错误。
在再次使用迭代器之前尝试倒回迭代器。
Presumably, the first call traverses all the elements in the iterator (i.e. calls next() until valid() is false). The sensible behaviour is for iterator_to_array to begin the conversion from the current position in the iterator - having it silently rewind would be inflexible, and possibly bug inducing.
Try rewinding the iterator before using it again.