gpt4 book ai didi

php - 更改为无限循环 while 循环

转载 作者:行者123 更新时间:2023-11-29 14:59:37 26 4
gpt4 key购买 nike

我有一个照片库,其中包含上一个链接和下一个链接。当到达最后一张图像时,它就停在那里。我希望它从第一张图片开始。该函数是一个 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);
}

最佳答案

我建议修改循环的 if 内容,如下所示。

$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评论修复了代码。愚蠢的错误

关于php - 更改为无限循环 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3581008/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com