更改为循环无限循环

时间:2010-08-27 02:48:04

标签: php mysql

我有一个包含上一个和下一个链接的照片库。当它到达最后一个图像时它停在那里。我想让它从第一张照片重新开始。该函数是一个for循环,我认为它应该是一个while循环,并且有些东西改变了,使它成为一个无限循环。我只是不知道如何转换这个功能。在PHP中仍然没那么强大。任何帮助表示赞赏。

$query  = "SELECT pho_id FROM album_photos WHERE alb_id='$alb_id' ORDER by srt_id ASC";
    $ret    = mysql_query($query);
    $num    = mysql_numrows($ret);
    for ($i = 0; $i < $num; $i++)
    {
        $row = trim(mysql_result($ret, $i));
        if ($row == $pho_id)
        {
                        $cur = $i;
            $forw = @trim(mysql_result($ret, ($i+1))) or $forw = NULL;
            $back = @trim(mysql_result($ret, ($i-1))) or $back = NULL;
        }

    }
$query = "SELECT * FROM photos WHERE pho_id='$back'";
        $rets  = mysql_query($query);
        $back_good = mysql_numrows($rets);

        $query = "SELECT * FROM photos WHERE pho_id='$forw'";
        $rets  = mysql_query($query);
        $forw_good = mysql_numrows($rets);

    $back = "photo-$per_id-$back-$alb_id.html";
    $forw = "photo-$per_id-$forw-$alb_id.html";

    if (strstr($back, 'pho_id=&') || $back_good == 0) { $back = NULL; }
    if (strstr($forw, 'pho_id=&') || $forw_good == 0) { $forw = NULL; }
    $ret = array();

    $ret['back'] = $back;
    $ret['next'] = $forw;
    $cur++;
    $ret['viewing']   = "Photo $cur of ".($num);

    if($ret['back'] == NULL){
    $ret['back'] = "";
    $spacer = str_repeat('&nbsp;',12);
    }
    if($ret['next'] == NULL){
    $ret['next'] = "";
    $spacer = str_repeat('&nbsp;',12);
    }

1 个答案:

答案 0 :(得分:1)

如果像这样的内容,我建议修改你的循环。

$cur = $i;

//compute the indexes of the next and previous elements
//the next item is the first if we are at the end.
$forward_index = $i == $num - 1 ? 0 : $i + 1; 
//the previous one is the last if we are at the beginning.
$backward_index = $i === 0 ? $num - 1 : $i - 1;

//fetch the elements
$forw = @trim(mysql_result($ret, $forward_index));
$back = @trim(mysql_result($ret, $backward_index));

//exit the for loop
break;

确实可以将for循环转换为while循环。但是,并非绝对需要这样做。我添加了一个break语句,以便在找到要加载的元素后立即退出。

编辑:根据OP评论修复了代码。愚蠢的错误