0

I'd like to traverse a resultset using a while() loop instead the most common foreach()

If I have this code for example:

$articles = $this->Articles->find();
foreach ($articles as $article) {
   echo $article->name;
}

How can I access rows of $articles using a while loop ?

I already tried traverse it using next() or $articles->next() with no success.

4
  • Why would you want to do that anyways?
    – ndm
    Commented Jul 23, 2017 at 13:37
  • I need to perform a control-break logic (en.wikipedia.org/wiki/Control_break) old fashioned ? :)
    – wnasich
    Commented Jul 23, 2017 at 14:32
  • I see, but shouldn't that be possible with a foreach loop too? In any case, if applicable I'd probably suggest to use the result sets grouping functionality.
    – ndm
    Commented Jul 23, 2017 at 14:49
  • Thanks for your answer, I am trying the grouped approach also.
    – wnasich
    Commented Jul 23, 2017 at 15:09

1 Answer 1

1

I'm not sure that you really need to use a while() loop for what you're trying to achieve, but to answer the question, you have to first get the result set, and then use its Iterator::valid() implementation for the loop condition, this is where the current result is being fetched, which you can then access via current(). Advancing the cursor is then being done using next().

$query = $this->Articles->find();
$resultSet = $query->all();

while ($resultSet->valid()) {
    $article = $resultSet->current();
    // ...
    $resultSet->next();
}

See also API > \Cake\ORM\ResultSet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.