我正在尝试使用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;
}
}
?>
答案 0 :(得分:4)
问题是您在next($images)
语句中使用foreach ($images ...)
,因此修改了内部数组指针。正如documentation on 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 =>
有人可能会认为只用next()
取代current()
会有所帮助,但唉:
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 ($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 =>
PHP 5.5.20的输出。
答案 1 :(得分:-1)
$images = sort(glob($dirname . "*.jpg"));