从当前位置获取数组中的上一个和下一个键/值(PHP)

时间:2017-10-05 04:57:04

标签: php arrays indexing key

我有一个类似于以下的数组:

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];

3 个答案:

答案 0 :(得分:1)

您可以{/ 3}}使用

$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);

答案 1 :(得分:0)

试一试。

   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];

答案 2 :(得分:0)

为了澄清之前的答案,使用关联数组,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