doutuan4361 2011-05-10 15:37
浏览 40
已采纳

用do..while,继续?

<?php
// initial value

$week = 50;
$year = 2001;
$store = array();
do
  {
  $week++;
  $result = "$week/$year";
  array_push($store,$result);
  if($week == 53){
    $week = 0;
    $year++;//increment year by 1
    }
    continue;
  }
// End of Loop
while ($result !== "2/2002");

?>

print_r($store);

result want return will be

array("51/2001", "52/2001", "01/2002", "02/2002");

What is my problems by using while using do..while ,continue?

  • 写回答

2条回答 默认 最新

  • du5114 2011-05-10 15:41
    关注
    • Your arguments to array_push are the wrong way around. Read the manual entry for functions you use. Turn on warnings on your server; running this in codepad showed me the problem immediately. [Edit: You have now quietly fixed that in your question.]
    • You also have a typo: $i instead of $week.
    • Finally, you test against "02/2002", but for that month the string will be "2/2002".

    Fixed code (live demo):

    <?php
    // initial value
    
    $week = 50;
    $year = 2001;
    $store = array();
    do
      {
      $week++;
      $result = "$week/$year";
      array_push($store, $result);
      if($week == 53){
        $week = 0;
        $year++;//increment year by 1
        }
        continue;
      }
    // End of Loop
    while ($result !== "2/2002");
    ?>
    

    In general, I'd recommend against loops like this. As you've discovered, your code is very fragile because you're testing for just one very specific value, and if that value is not precisely correct you get an infinite loop.

    Instead, consider comparing $week and $year separately and numerically:

    while ($week < 2 && $year <= 2002)
    

    Next time please include in your question the output that you are seeing, as well as the output that you want to see. It'll save us time in reproducing your problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计