数组得到下一个/前一个元素

Sot*_*tos 2 php arrays

我有这个id的数组:$ products = array(2151,2563,2015,1986,1985);

我想要的是构建一个函数,每次我传递一个id时,它将返回下一个和前一个项目.例如,当我让我们说2563-id获得2151和2015的回复时.

任何建议将不胜感激.

Rol*_*ruz 7

$index = array_search($id, $products);
if($index !== FALSE)
{
  $next = $products[$index + 1];
  $previous = $products[$index - 1];
}
Run Code Online (Sandbox Code Playgroud)

然后你做检查,因为$products[$index +/- 1]不会永远存在!