我正在尝试使用PHP制作一个画廊。图像加载正常,但下一个和上一个按钮似乎不起作用。点击下一个图片#1会把你带到图片#3,但点击回到图片#3会把你带到图片#2,这是正确的。我应该如何修改我的代码,使两者都井然有序?
<?php
function listPicturesInDir($dir) {
$dirname = "../pictures/photos/" . $dir . "/";
$images = glob($dirname . "*.jpg");
$previousPic = "null";
foreach ($images as $image) {
$next = next($images);
$name = str_replace(".jpg", "", $image);
$fp = strrpos($name, '/', 5) + 1;
$name = substr($name, $fp, strlen($name));
$id = str_replace(" ", "", $name);
echo '<a href="#' . $id . '"><img class="galleryPics" src="' . $image . '" alt = "' . $name . '" title="'. $name.'"/></a>';
echo '<div id="' . $id . '" class="modalDialog">';
echo '<div>';
if($previousPic !== "null"){
echo'<a href="#'.$previousPic . '"><img src="../pictures/arrowLeft2.png" alt="Previous photograph" title= "Previous photograph" class="arrow"/></a> ';
}
if($next !== false){
$name_next = str_replace(".jpg", "", $next);
$fp_next = strrpos($name_next, '/', 5) + 1;
$name_next2 = substr($name_next, $fp_next, strlen($name_next));
$id_next = str_replace(" ", "", $name_next2);
echo'<a href="#'.$id_next . '"><img src="../pictures/arrowRight2.png" alt="Next photograph" title="Next photograph" class="arrow"/></a>';
}
echo '<a href="#close" title="Close" class="close">X</a>';
echo '<h2>' . $name . '</h2>';
echo '<img class="modalImg" src="' . $image . '" alt = "' . $name . '"/>';
echo '</div>';
echo '';
echo '</div>';
//echo $next;
$previousPic = $id;
}
}
?>
问题是您在foreach ($images ...)
语句中使用next($images)
,从而修改了内部数组指针。这个可能导致意想不到的行为,正如foreach:
由于foreach依赖于内部数组指针,因此在循环中更改它可能会导致意外行为。
使用foreach
和next
说明了您的问题:
$images = array('one', 'two', 'three', 'four');
foreach ($images as $image) {
$next = next($images);
echo "$image => $next", PHP_EOL;
}
输出:one => three
two => four
three =>
four =>
有人可能认为用current()
代替next()
会有帮助,但是唉:
foreach ($images as $image) {
$next = current($images);
echo "$image => $next", PHP_EOL;
}
输出:one => two
two => two
three => two
four => two
根据foreach
文档页面上的评论,该页面上曾经有一个通知说:
除非引用了数组,否则foreach操作的是指定数组的副本,而不是数组本身。foreach对数组指针有一些副作用。不要在foreach操作期间或之后依赖数组指针而不重置它。
不知道为什么它被删除了,但是如果我们使用$image
的引用,那么它实际上是有效的(注意&
):
foreach ($images as &$image) {
$next = current($images);
echo "$image => $next", PHP_EOL;
}
输出:one => two
two => three
three => four
four =>
但是也许老式的for循环更有意义:
for ($i = 0; $i < count($images); $i++) {
$nextIndex = $i + 1;
$next = ($nextIndex < count($images)) ? $images[$nextIndex] : null;
$image = $images[$i];
echo "$image => $next", PHP_EOL;
}
输出:one => two
two => three
three => four
four =>
$images = sort(glob($dirname . "*.jpg"));