php中goto的循环问题
我已经使用 goto 命令编写了一个脚本,但是在我想要执行该脚本的服务器上有一个以前的 PHP 版本(<5.3),所以我必须更改代码。代码的结构是这样的:
for($i = 0; $i < 30; $i++) // print 30 articles
{
$x = 0;
// choose a a feed from the db
// parse it
a:
foreach($feed->get_items($x, 1) as $item)
{
// create a unique id for the article of the feed
if($id == $dbid)
{
// if this id exists in the db, take the next article of the same feed which is not in the db
$x++;
goto a;
}
else
{
// print the original article you grabbed
}
} // end of foreach
} // end of for
我已经测试了所有内容。您有什么想法如何在没有 goto
的情况下重新转换此代码以便正确执行吗?
I have programmed a script with the goto
command but on the server where I want to execute the script there is a previous PHP version (<5.3), so I have to change the code. The structure of the code goes like that:
for($i = 0; $i < 30; $i++) // print 30 articles
{
$x = 0;
// choose a a feed from the db
// parse it
a:
foreach($feed->get_items($x, 1) as $item)
{
// create a unique id for the article of the feed
if($id == $dbid)
{
// if this id exists in the db, take the next article of the same feed which is not in the db
$x++;
goto a;
}
else
{
// print the original article you grabbed
}
} // end of foreach
} // end of for
I have tested everything. Do you have any ideas how can I retransform this code without goto
in order to be executed properly???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这个问题说明了为什么应该避免 goto。它可以让你不用考虑算法就可以摆脱困境。
执行此操作的标准方法是使用标志。我希望您没有期待“herezthecode kthxbai”之类的答案,但在这种情况下,解释它的最佳方法是编写代码 -
This questions demonstrates why goto should be avoided. It lets you get away without thinking about the algorithm enough.
The standard way to do this is with a flag. I hope you were not expecting a "herezthecode kthxbai" sort of an answer, but in this case the best way to explain it would be to write the code -
如果不知道
->get_items()
调用的行为方式,您可以使用这种强力方法来代替 goto-switch:标签被
while
替换,并且自我实现的停止条件。 goto 变成中断并重置$a
停止条件。Without knowing how the
->get_items()
call behaves you could use this brute-force method in lieu of the goto-switch:The label gets replaced by a
while
and a self-fulfulling stop condition. And the goto becomes a break and resets the$a
stop condition.像这样的东西可能会起作用......
对不起,我删除了所有评论,它们很烦人。
Something like this would probably work...
I'm sorry, I removed all the comments, they were annoying.
将 $x 的声明移到 for 循环之外,并用中断替换标签/goto 组合,如下所示......
Move the declaration of $x outside of the for loop and replace your label/goto combination with a break, like so...
同意 unset - 使用break将中断if循环并继续迭代for循环
Agree with unset - using break will break if loop and keep iterating through for loop