【问题标题】:Get the next array item using the key php使用键 php 获取下一个数组项
【发布时间】:2011-06-20 06:58:05
【问题描述】:

我有一个数组

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

【问题讨论】:

标签: php


【解决方案1】:
<?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;
?>

【讨论】:

    【解决方案2】:
    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));
    

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

    【讨论】:

    • 我喜欢第一个解决方案!漂亮。
    • @Nobita @deceze 不错,但我想知道如果在 $array 中找不到 $key 会发生什么?这不会造成无限循环吗?
    • @Berry 很好,添加了一个检查。
    • 当数组的当前键跟随在搜索键之后时,第一个函数不起作用。
    • 这个小功能太完美了,需要添加为原生PHP函数...
    【解决方案3】:

    你可以使用 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

    【讨论】:

      【解决方案4】:
      $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>");
      }
      

      【讨论】:

        【解决方案5】:

        你可以这样打印:-

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

        【讨论】:

        • @Karolis 可能是我写得很快.. :)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-27
        • 1970-01-01
        • 2019-04-29
        • 1970-01-01
        • 2018-03-16
        • 1970-01-01
        相关资源
        最近更新 更多