PHP数组的下一个值的值


PHP array next value of a value

如何从数组中获取值的下一个值。我有一个这样的数组

 $items = array(
    '1'   => 'two',
    '9'   => 'four',
    '7' => 'three',
    '6'=>'seven',
    '11'=>'nine',
    '2'=>'five'        
);

如何获取' 4 '或' 9 '的下一个值

我有这个

$input = "nine";
$items = array(
    '1'   => 'two',
    '9'   => 'four',
    '7' => 'three',
    '6'=>'seven',
    '11'=>'nine',
    '2'=>'five'
);
$keys = array_keys($items);
$size = count($keys);
$foundKey = array_search($input,$items);
if($foundKey !== false)
{
    $nextKey = array_search($foundKey,$keys)+1;
        echo "your input is: ".$input."'n";
        echo "it's key is: ".$foundKey."'n";
    if($nextKey < $size)
    {
        echo "the next key => value is: ".$keys[$nextKey]." => ".$items[$keys[$nextKey]]."'n";
    }
    else
    {
        echo "there are no more keys after ".$foundKey;
    }
}

的想法是,因为键没有任何实际的顺序,我需要通过获取所有键并将它们放入一个数组来使它们的整数键是我们的顺序,从而使遍历顺序变得容易。这样,'1' = 0, '9' = 1, '11' = 4。

然后从

中找到与输入匹配的键。如果我找到它,我得到那个键的位置和+ 1(下一个键)。从那里,我可以使用$keys中的字符串值在我们输入的位置+1引用$items中的数据。

如果输入是'five',则会遇到问题,因为'five'是数组中的最后一个值。所以最后一个if语句检查下一个键的索引是否小于键数,因为最大的索引是5,键数是6。

虽然您可以使用array_values使用有序整数键将所有值放入数组中,但这样做会丢失原始键,除非您也使用array_keys。如果你先用array_keys,那就没必要再用array_values

希望对您有所帮助:

while (($next = next($items)) !== NULL) {   
    if ($next == 'three') {     
        break;      
    }
}
$next = next($items);
echo $next;

对于大数组u可以使用:

$src = array_search('five',$items); // get array key
$src2 = array_search($src,array_keys($items)); // get index array (start from 0)
$key = array_keys($items); // get array by number, not associative anymore

// then what u need just insert index array+1 on array by number ($key[$src2+1])
echo $items[$key[$src2+1]];

如果是这种情况,您应该首先准备您的数组。根据您给定的数组,似乎索引不是连续正确的。尝试使用array_values()函数

$items = array(
    '1'   => 'two',
    '9'   => 'four',
    '7' => 'three',
    '6'=>'seven',
    '11'=>'nine',
    '2'=>'five'        
);
$new_items = array_values($items);
$new_items = array(
    [0] => 'two',
    [1] => 'four',
    [2] => 'three',
    [3] => 'seven',
    [4] => 'nine',
    [5] =>'five'        
);

然后你可以做foreach…

foreach($new_items as $key => $value) {
   // Do the code here using the $key
}