PHP get previous array element knowing current array key

前端 未结 9 774
心在旅途
心在旅途 2020-12-01 06:41

I have an array with specific keys:

array(
    420 => array(...), 
    430 => array(...), 
    555 => array(...)
)

In my applicati

相关标签:
9条回答
  • 2020-12-01 07:11

    This is a simple solution for taking previous and next items, even if we are at the ends of the array.

    <?php
    
    $current_key; // the key of the item we want to search from
    
    if (isset($array[$current_key+1])) 
    {
      // get the next item if there is 
      $array_next = $array[$current_key+1];
    } 
    else 
    {       
       // if not take the first (this means this is the end of the array)
      $array_next = $array[0];
    }       
    
    if (isset($array[$current_key-1])) 
    {
       // get the previous item if there is
       $array_prev = $array[$current_key-1]; 
    } 
    else 
    {   
      // if not take the last item (this means this is the beginning of the array)
      $array_prev = $array[count($array)-1];        
    }
    
    0 讨论(0)
  • 2020-12-01 07:11

    Expanding further on the solution of Luca Borrione and cenk, so that you can wrap around the end of the array in either direction, you may use:

    function getAdjascentKey($key, $hash = array(), $increment) {
        $keys = array_keys($hash);    
        $found_index = array_search($key, $keys);
        if ($found_index === min(array_keys($keys)) && $increment === -1) {
            $found_index = max(array_keys($keys))+1;
        }
        if ($found_index === max(array_keys($keys)) && $increment === +1) {
            $found_index = min(array_keys($keys))-1;
        }       
        return $keys[$found_index+$increment];
    }
    
    0 讨论(0)
  • 2020-12-01 07:13

    You can iterate through the array in reverse and return the next iteration after finding the search value.

    $found = false;
    foreach(array_reverse($array, true) as $key=>$value) {
      if ($found) {
        print "$key => $value\n";
        break;
      } else if ($key == 555) {
        $found = true;
      }
    }
    

    http://ideone.com/2WqmC

    0 讨论(0)
提交回复
热议问题