使用数组 next() 和 prev() 链接进行图像导航


Image navigation with arrays next() and prev() links

我正在尝试使用此函数进行图像导航:

function array_key_relative($array, $current_key, $offset = 1, $strict = true) {
  // create key map
  $keys = array_keys($array);
  // find current key
  $current_key_index = array_search($current_key, $keys, $strict);
  // return desired offset, if in array, or false if not
  if(isset($keys[$current_key_index + $offset])) {
    return $keys[$current_key_index + $offset];
  }
  return false;
}

我想这样使用它:

<?php 
$images = array();
foreach ($images as $key => $image)
$prev_key = $this->array_key_relative($images, $key, -1);
$next_key = $this->array_key_relative($images, $key, 1);
?>

<a href="<?php echo "image?id=".$images[$prev_key]->id; ?>">Prev</a>
<a href="<?php echo "image?id=".$images[$next_key]->id; ?>">Next</a>

问题是当我按下一步或上一个链接它只工作一次时,例如,如果当前键是 1,如果我按下一步将转到 2,但一旦我在 2 页面上导航停止工作(不转到 3、4、5 等)。有人指出我正确的方向吗?谢谢。

您的next_key乍一看时不包含 + 符号 -

$next_key = $this->array_key_relative($images, $key, +1);

但我会使用

$next = $images++; 
$prev = $images--;

$next_key = $this->array_key_relative($images, $key, $next);
$prev_key = $this->array_key_relative($images, $key, $prev);