替换循环 [英] Replacing Do ... While Loops
问题描述
我有下面的代码片段从PHP手册中的curl_multi_ *条目:
I have the following piece of code taken from the PHP manual on the curl_multi_* entries:
$active = null;
do {
$process = curl_multi_exec($curl, $active);
} while ($process === CURLM_CALL_MULTI_PERFORM);
while (($active >= 1) && ($process === CURLM_OK))
{
if (curl_multi_select($curl, 3) != -1)
{
do {
$process = curl_multi_exec($curl, $active);
} while ($process === CURLM_CALL_MULTI_PERFORM);
}
}
现在的东西是我真的不喜欢写do ... while循环,我想知道什么是最好的和更短的方式来完成相同,但没有使用这种循环。
Now the thing is I really don't like writing do...while loops and I was wondering what would is the best and shorter way to accomplish the same but without using this kind of loops.
到目前为止,提出了一个稍长的版本,但我不知道它是否完全相同,或者如果它执行与原来的方式相同的方式:
So far I've come up with a slightly longer version but I'm not sure if it does exactly the same or if it performs the same way as the original one:
while (true)
{
$active = 1;
$process = curl_multi_exec($curl, $active);
if ($process === CURLM_OK)
{
while (($active >= 1) && (curl_multi_select($curl, 3) != -1))
{
$process = CURLM_CALL_MULTI_PERFORM;
while ($process === CURLM_CALL_MULTI_PERFORM)
{
$process = curl_multi_exec($curl, $active);
}
}
break;
}
else if ($process === CURLM_CALL_MULTI_PERFORM)
{
continue;
}
break;
}
提前感谢。
推荐答案
Do..While
循环接近精确到 While
,除了它们确保 Do..While
循环中至少执行一次 的代码。因此,转换 Do..While
循环的简单方法是从 Do..While
中拉出代码它执行一次并转换为 While
。
Do..While
loops are near exact to While
loops, except that they ensure the code within the Do..While
loop executes at least once. So the simple way to convert Do..While
loops is to pull out the code from the Do..While
so that it executes once and convert to While
.
do {
action();
} while(...)
等效于:
action();
while(...) {
action();
}
这样应用于您的代码,更改将如下所示:
So applied to your code the change would look like:
$active = null;
$process = curl_multi_exec($curl, $active);
while ($process === CURLM_CALL_MULTI_PERFORM) {
$process = curl_multi_exec($curl, $active);
}
while (($active >= 1) && ($process === CURLM_OK))
{
if (curl_multi_select($curl, 3) != -1)
{
$process = curl_multi_exec($curl, $active);
while ($process === CURLM_CALL_MULTI_PERFORM) {
$process = curl_multi_exec($curl, $active);
};
}
}
$ c> Do..While 循环,你应该使用它们,如果你需要。
With that said, there's nothing wrong with Do..While
loops and you should use them if you need to.
这篇关于替换循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!