将查询结果遍历到 while 循环中
Traverse a query result into a while loop
我想使用 while() 循环而不是最常见的 foreach()[=11= 来遍历结果集]
如果我有这个代码,例如:
$articles = $this->Articles->find();
foreach ($articles as $article) {
echo $article->name;
}
如何使用 while 循环访问 $articles 行?
我已经尝试使用 next() 或 $articles->next() 遍历它,但没有成功。
我不确定您是否真的需要使用 while()
循环来实现您想要实现的目标,但要回答这个问题,您必须先获取结果集,然后使用它的 Iterator::valid()
循环条件的实现,这是获取当前结果的地方,然后您可以通过 current()
访问它。然后使用 next()
.
推进光标
$query = $this->Articles->find();
$resultSet = $query->all();
while ($resultSet->valid()) {
$article = $resultSet->current();
// ...
$resultSet->next();
}
我想使用 while() 循环而不是最常见的 foreach()[=11= 来遍历结果集]
如果我有这个代码,例如:
$articles = $this->Articles->find();
foreach ($articles as $article) {
echo $article->name;
}
如何使用 while 循环访问 $articles 行?
我已经尝试使用 next() 或 $articles->next() 遍历它,但没有成功。
我不确定您是否真的需要使用 while()
循环来实现您想要实现的目标,但要回答这个问题,您必须先获取结果集,然后使用它的 Iterator::valid()
循环条件的实现,这是获取当前结果的地方,然后您可以通过 current()
访问它。然后使用 next()
.
$query = $this->Articles->find();
$resultSet = $query->all();
while ($resultSet->valid()) {
$article = $resultSet->current();
// ...
$resultSet->next();
}