简体   繁体   English

while循环的替代方法?

[英]Alternative of do while loop?

I came across a piece of code which runs through a method which fetches results from a query(table is having 130000 records) and is using do while loop to do this. 我遇到了一段代码,该代码通过一种方法来运行,该方法从查询中获取结果(表有130000条记录),并使用do while循环来执行此操作。

public function updateTestData()
{
    $limit = 1000;
    $offset = 0;
    $processedCount = 1;

    do {
        $idList = $this->getActiveIds($limit, $offset);

        if (array() === $idList) {
            break;
        }

        $count = count($idList);
        $this->getLogger()->log("Fetching $count ids from db..", Zend_Log::DEBUG);

        foreach ($idList as $contactId) {
            //doing few log things
            $processedCount++;
        }

        $offset = $offset + $limit;
    } while (true);
}

Is this the right way to do this? 这是正确的方法吗? Or is there any better way of writing this method avoiding an infinite do while loop? 还是有更好的方法编写这种方法来避免无限次的while循环? Any help would greatly be appreciated. 任何帮助将不胜感激。

No need for a do-while , you can simply use while with the method as your condition since it will return a false condition when the array is empty. 不需要do-while ,您只需将while用作条件即可,因为当数组为空时它将返回假条件。 I would do the following: 我将执行以下操作:

$limit = 1000;
$offset = 0;
$processedCount = 1;

while ($idList = $this->getActiveIds($limit, $offset)) {
    $processedCount += count($idList);
    $offset += $limit;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM