【问题标题】:Getting the previous and next keys/values in array from current position (PHP)从当前位置获取数组中的上一个和下一个键/值(PHP)
【发布时间】:2018-03-16 15:06:24
【问题描述】:

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

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

【问题讨论】:

  • 这并不难。你有没有尝试过?
  • 我尝试了 current、prev 和 next 函数,但它们不起作用,因为当前函数返回数组中的第一项,而不是我选择的起点。

标签: php arrays indexing key


【解决方案1】:

您可以为此使用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);

【讨论】:

  • 我知道这些函数存在,但当前函数返回数组中的第一项,而不是我选择的任意键。
  • 您需要遍历数组以将指针设置在您想要的位置
  • 如何停止循环,一旦我找到了密钥,以这样一种方式 current() 将返回该密钥, prev() 上一个和 next() 下一个?
  • 做 prev() 和 next() 循环,如果 current() 是数组中的最后一项,那么 next() 会移动到数组中的第一项?
  • 我只是遇到了这样一种情况,即循环永远持续下去,或者直到 PHP 杀死它,当找不到值时。
【解决方案2】:

试试这个。

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 2016-06-07
      • 2011-06-15
      • 2022-01-16
      • 1970-01-01
      • 2015-11-14
      相关资源
      最近更新 更多