获取前面和后面的键/从当前位置在数组值(PHP)

问题描述:

我有类似如下的数组:获取前面和后面的键/从当前位置在数组值(PHP)

const BookIndex = array 
(
    '1' => 'Chapter 1', 
    '1.1' => 'Chapter 1.1', 
    '1.1.1' => 'Chapter 1.1.1', 
    '2' => 'Chapter 2', 
    '2.1' => 'Chapter 2.1', 
    '2.1.1' => 'Chapter 2.1.1', 
); 

比方说,我莫名其妙地确定当前键(位置)我关心是'2'键。我如何找到上一个和下一个键?

$CurrentKey = '2'; 
$CurrentValue = BookIndex[$CurrentKey]; 

$PreviousKey = null; // I need to figure out the previous key from the current key. 
$PreviousValue = BookIndex[$PreviousKey]; 

$NextKey = null; // I need to figure out the next key from the current key. 
$NextValue = BookIndex[$NextKey]; 
+1

这不是非常困难。你有尝试过什么吗? –

+0

我尝试了当前,前一个和下一个函数,但它们不起作用,因为当前函数返回数组中的第一个项目,而不是我选择的起点。 – user8056359

您可以使用array functions

$NextKey = next($BookIndex); // next key of array 

$PreviousKey = prev($BookIndex); // previous key of array 

$CurrentKey = current($BookIndex); // current key of array 

指向特定位置

$CurrentKey = '2'; 

while (key($BookIndex) !== $CurrentKey) next($BookIndex); 
+0

我知道这些函数存在,但当前函数返回数组中的第一个项目,而不是我选择的任意键。 – user8056359

+0

你需要遍历数组来设置你想要的位置上的指针 –

+0

如何在找到密钥后停止循环,使current()返回该密钥prev()前一个下一个()下一个? – user8056359

尝试了这一点。

function get_next_key_array($array,$key){ 
     $keys = array_keys($array); 
     $position = array_search($key, $keys); 
     if (isset($keys[$position + 1])) { 
      $nextKey = $keys[$position + 1]; 
     } 
     return $nextKey; 
    } 

    function get_previous_key_array($array,$key){ 
     $keys = array_keys($array); 
     $position = array_search($key, $keys); 
     if (isset($keys[$position - 1])) { 
      $previousKey = $keys[$position - 1]; 
     } 
     return $previousKey; 
    } 


    $CurrentKey = '2'; 
    $CurrentValue = BookIndex[$CurrentKey]; 

    $PreviousKey = get_previous_key_array($BookIndex,$CurrentKey) 
    $PreviousValue = BookIndex[$PreviousKey]; 

    $NextKey = get_next_key_array($BookIndex,$CurrentKey) 
    $NextValue = BookIndex[$NextKey]; 

只是为了澄清以前的答案,连同关联数组,next()prev()函数返回下一个或以前的值 - 不是关键 - 关于你的问题。

假设您的$BookIndex阵列。如果要移动,并获得下一个值(或以前),你可以这样做:

$nextChapter = next($BookIndex); // The value will be 'Chapter 1.1' 
$previousChapter = prev($nextChapter); // The value will be 'Chapter 1' 

更多,next()prev()函数期望参数为array,不是const