PHP密钥=> value array查找上一个和下一个条目

时间:2011-03-21 10:33:21

标签: php arrays search

我有一个带key =>的数组值,我想收到给定数组键的上一个和下一个条目。

示例:

$array = array(
    'one'   => 'first',
    'two'   => 'second',
    'three' => '3rd',
    'four'  => '4th'
)

当我收到指定的密钥'two'时,我希望收到条目$array['one']$array['three'],是否有任何不错的无预告解决方案

4 个答案:

答案 0 :(得分:3)

您要查找的两个功能是next()prev()。本机PHP函数可以完全满足您的要求:

$previousPage = prev($array);
$nextPage = next($array);

这些函数移动内部指针,例如,如果你在$ array ['two']并使用prev($ array),那么你现在在$ array ['one']上。我得到的是,如果你需要得到一个和三个,那么你需要调用next()两次。

答案 1 :(得分:1)

$array = array(
    'one'   => 'first',
    'two'   => 'second',
    'three' => '3rd',
    'four'  => '4th'
);


function getPrevNext($haystack,$needle) {
    $prev = $next = null;

    $aKeys = array_keys($haystack);
    $k = array_search($needle,$aKeys);
    if ($k !== false) {
        if ($k > 0)
            $prev = array($aKeys[$k-1] => $haystack[$aKeys[$k-1]]);
        if ($k < count($aKeys)-1)
            $next = array($aKeys[$k+1] => $haystack[$aKeys[$k+1]]);
    }
    return array($prev,$next);
}

var_dump(getPrevNext($array,'two'));

var_dump(getPrevNext($array,'one'));

var_dump(getPrevNext($array,'four'));

答案 2 :(得分:0)

您可以尝试使用SPL CachingIterator的实现来解决问题。

答案 3 :(得分:0)

您可以定义自己的类来处理基本数组操作:

以下是adityabhai发布的一个例子[at] gmail com [Aditya Bhatt] 09-May-2008 12:14发布于php.net

<?php
class Steps {

    private $all;
    private $count;
    private $curr;

    public function __construct () {

      $this->count = 0;

    }

    public function add ($step) {

      $this->count++;
      $this->all[$this->count] = $step;

    }

    public function setCurrent ($step) {

      reset($this->all);
      for ($i=1; $i<=$this->count; $i++) {
        if ($this->all[$i]==$step) break;
        next($this->all);
      }
      $this->curr = current($this->all);

    }

    public function getCurrent () {

      return $this->curr;

    }

    public function getNext () {

      self::setCurrent($this->curr);
      return next($this->all);

    }

    public function getPrev () {

      self::setCurrent($this->curr);
      return prev($this->all);

    }

  }
?>

Demo Example:

<?php
   $steps = new Steps();
   $steps->add('1');
   $steps->add('2');
   $steps->add('3');
   $steps->add('4');
   $steps->add('5');
   $steps->add('6');
   $steps->setCurrent('4');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   echo $steps->getPrev()."<br />";
   $steps->setCurrent('2');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   echo $steps->getPrev()."<br />";
?>