dtvpe4837413 2016-07-27 13:18
浏览 38
已采纳

ArrayIterator的valid()始终显示为true

I have a problem with ArrayIterator::valid() method. It always return true. I don't know if I don't understand how should it work, or am I doing something wrong...

I use Doctrine's Paginator
http://www.doctrine-project.org/api/orm/2.1/source-class-Doctrine.ORM.Tools.Pagination.Paginator.html

It does implement \Countable and \IteratorAggregate. The method getIterator() returns \ArrayIterator.

In view I do:

<?php foreach ($this->paginator as $message): ?>
    <?php var_dump($this->paginator->valid()); ?> // Fatal error. Method does not exist
    <?php var_dump($this->paginator->getIterator()->valid()); ?> // <-- it always return true
    <p>Teeeeeest</p>
<?php endforeach; ?>

I also tried:

<?php $paginator = $this->paginator->getIterator(); ?>
<?php foreach ($paginator as $message): ?>
    <?php var_dump($paginator->valid()); ?> // <-- it always return true
    <p>Teeeeeest</p>
<?php endforeach; ?>

var_dump($this->paginator) shows that I have 2 records. So I should get true in first iteration and false in second iteration. Am I correct? So why does it return always true

  • 写回答

1条回答 默认 最新

  • duanming7833 2016-07-27 13:39
    关注

    The foreach takes only valid entries, so $paginator->valid() is always valid at this point. If you use $paginator->next() that will end in false after the last entry was proccessed.

    So $paginator->valid() is used with $paginator->next() not within a foreach

    Try to test it like that.

    $paginator->reset();
    while($paginator->valid()){
        $entrie = $paginator->current();
    
        $paginator->next();
    }
    

    or test it with var_dump($paginator->valid()); after the foreach. (But maybe the foreach will reset the iterator after iteration)

    :-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决