使用密钥php获取下一个数组项

时间:2011-06-20 06:58:05

标签: php

我有一个数组

Array(1=>'test',9=>'test2',16=>'test3'... and so on);

如何通过传递密钥来获取下一个数组项。

例如,如果我有密钥9,那么我应该得到test3作为结果。如果我有1,那么它应该返回'test2'作为结果。

编辑以使其更清晰

echo  somefunction($array,9); //result should be 'test3'
function somefunction($array,$key)
{
  return $array[$dont know what to use];
}

5 个答案:

答案 0 :(得分:28)

function get_next($array, $key) {
   $currentKey = key($array);
   while ($currentKey !== null && $currentKey != $key) {
       next($array);
       $currentKey = key($array);
   }
   return next($array);
}

或者:

return current(array_slice($array, array_search($key, array_keys($array)) + 1, 1));

如果搜索的密钥不存在,则很难用第二种方法返回正确的结果。请谨慎使用。

答案 1 :(得分:1)

你可以使用next();函数,如果你想获得下一个数组的元素。

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

<强>更新

如果你想检查并使用下一个元素,你可以尝试:

创建一个函数:

function has_next($array) {
    if (is_array($array)) {
        if (next($array) === false) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

称之为:

if (has_next($array)) {
    echo next($array);
}

来源:php.net

答案 2 :(得分:0)

$array = array("sony"=>"xperia", "apple"=>"iphone", 1 , 2, 3, 4, 5, 6 );

foreach($array as $key=>$val)
{
    $curent = $val;
    if (!isset ($next))
        $next = current($array);
    else
        $next = next($array);
    echo (" $curent | $next <br>");
}

答案 3 :(得分:0)

<?php
$users_emails = array(
'Spence' => 'spence@someplace.com', 
'Matt'   => 'matt@someplace.com', 
'Marc'   => 'marc@someplace.com', 
'Adam'   => 'adam@someplace.com', 
'Paul'   => 'paul@someplace.com');

$current = 'Paul';
$keys = array_keys($users_emails);
$ordinal = (array_search($current,$keys)+1)%count($keys);
$next = $keys[$ordinal];
echo $next;
?>

答案 4 :(得分:-1)

您可以这样打印: -

foreach(YourArr as $key => $val)
{  echo next(YourArr[$key]); 
  prev(YourArr); }
相关问题