循环问题与goto在PHP中

时间:2011-06-04 16:48:34

标签: php loops 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的情况下重新转换此代码才能正确执行???

5 个答案:

答案 0 :(得分:2)

这个问题说明了为什么要避免使用goto。它可以让你在不考虑算法的情况下逃脱。

执行此操作的标准方法是使用标记。我希望你没有期待一个“herezthecode kthxbai”的答案,但在这种情况下解释它的最好方法是编写代码 -

for($i=0;$i<30;$++){
  $x=0;
  do {
    $found = false;
    foreach($feed->get_items($x,1) as $item){
      // get $id
      if($id==$dbid){
        $found = true;
        break;
      }else{
        // other things
      }
    }
    $x++;
  } while($found);
}

答案 1 :(得分:1)

在不知道->get_items()调用的行为方式的情况下,您可以使用这种强力方法代替goto-switch:

for($i = 0; $i < 30; $i++)
{
    $x = 0;


    $a = 1;
    while ($a--)
    foreach($feed->get_items($x, 1) as $item)
    {

      if($id == $dbid)
      {
          $x++;
          $a=1; break;
      }
      else
      {
      }

   } // end of foreach
} // end of for

标签被while和自我满足的停止条件取代。并且goto变为休息并重置$a停止条件。

答案 2 :(得分:0)

这样的事可能有用......

function loop(){
  foreach($feed->get_items($x,1) as $item){
    if($id==$dbid){
      $x++;
      loop();
    }else{

    }
  }
}
for($i=0;$i<30;$++){
  $x=0;
  loop();
}

对不起,我删除了所有评论,他们很讨厌。

答案 3 :(得分:0)

将$ x的声明移到for循环之外,并用break替换你的label / goto组合,就像这样......

    $x=0;
    for($i=0;$i<30;$++)  //print 30 articles 
    {
     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++;
          continue;
       }
       else
       {
         //print the original article you grabbed
       }

     } // end of foreach
   }//end of for

答案 4 :(得分:-1)

同意未设置 - 如果循环使用break将中断并继续迭代for循环