Search code examples
cakephpormiteratorresultsetcakephp-3.x

Traverse a query result into a while loop


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.


Solution

  • 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