duanke9540 2012-01-28 13:52
浏览 43
已采纳

处理无限循环

I'm trying to learn PHP programming through trial, error and lots and lots of practice. I've been working on a directory bases image gallery for the last few days and it seems to work fine. I can upload pictures and create new albums. Plus whenever I see a full size picture I have links to the previous and next pictures in the directory.

Now this is where I ran into problems. Once you got to the end of the directory the code would start an infinite loop while it searches for the next file, which isn't there.

So I altered my code and it now looks something like this:

$x = 1;
$dir = opendir($base.'/'.$get_album);
while ((($file = readdir($dir)) !== FALSE) && ($x == 1)) {
  while ($img < $file) {
    $img++;
    $image_exists = file_exists($base.'/'.$get_album.'/'.$img);
    if ($image_exists) {
      echo "<a href='member.php?album=$get_album&imgID=$img'>
              <img src='$base/$get_album/$img' width='70' align='right'>
            </a>";
      break;
    }
    $x++;
  }
}

This works when I get to the last picture in the directory. So I thought I'd do the same for when I get to the first picture and just invert the operators like so:

$x = 1;
$dir = opendir($base.'/'.$get_album);
while ((($file = readdir($dir)) !== FALSE) && ($x == 1)) {
  while ($img > $file) {
    $img--;
    $image_exists = file_exists($base.'/'.$get_album.'/'.$img);
    if ($image_exists) {
      echo "<a href='member.php?album=$get_album&imgID=$img'>
              <img src='$base/$get_album/$img' width='70' align='right'>
            </a>";
      break;
    }
    $x++;
  }
}

This however DOES NOT work. I can't understand why that would be the case and I've tried to change things around a few dozen times but I cant seem to make it stop looping.

What am I doing wrong?

Thanks in advance for your help (and for reading through all this).

  • 写回答

3条回答 默认 最新

  • duanjia6959 2012-01-28 14:09
    关注

    The issue could likely be related to the fact that readdir returns a string, and you are treating it as if you know its a number. You might find that it is returning you something at the start or end, such as the parent directory '..' as a string or the current directory as a string '.'.

    If you want to iterate over the directories, you should check that the return value from readdir is not '.' or '..' specifically.

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

报告相同问题?

悬赏问题

  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并