PHP get previous array element knowing current array key

前端 未结 9 773
心在旅途
心在旅途 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 06:48

    If your data is large then it might be a best practice to avoid looping. You could make your own custom function, like so:

    $array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
    
    function previous($key, $array) {
      $keysArray = array_keys($array);
      $keyNumber = array_search($key, $keysArray);
      if ($keyNumber === 0) {
        $keyNumber = count($array);
      }
      return $array[$keysArray[$keyNumber - 1]];
    }
    var_dump(previous("second", $array));
    

    Note that if you provide first key then it will return the last value, like a cyclic array. You can handle it however you like.

    With a bit tweak, you can also generalize it to return next values.

    As for why prev isnt working is because it isnt used for that purpose. It just sets the internal pointer of the array to one behind, exact inverse of next

    I hope it helps

    0 讨论(0)
  • 2020-12-01 06:50

    @Luca Borrione's solution was helpful. If you want to find both previous and next keys, you may use the following function:

    function getAdjascentKey( $key, $hash = array(), $increment ) {
        $keys = array_keys( $hash );    
        $found_index = array_search( $key, $keys );
        if ( $found_index === false ) {
            return false;
        }
        $newindex = $found_index+$increment;
        // returns false if no result found
        return ($newindex > 0 && $newindex < sizeof($hash)) ? $keys[$newindex] : false;
    }
    

    Usage:

    // previous key
    getAdjascentKey( $key, $hash, -1 );
    
    // next key
    getAdjascentKey( $key, $hash, +1 );
    

    Examples:

    $myhash = array(
        'foo' => 'foovalue',
        'goo' => 'goovalue',
        'moo' => 'moovalue',
        'zoo' => 'zoovalue'
    );
    
    getAdjascentKey( 'goo', $myhash, +1 );
    // moo
    
    getAdjascentKey( 'zoo', $myhash, +1 );
    // false
    
    getAdjascentKey( 'foo', $myhash, -1 );
    // false
    
    0 讨论(0)
  • 2020-12-01 06:51

    Just iterate over the array

    $_index = null;
    foreach($myarray as $index => $value)
    {
        if($key == $my_index) // if($key == 550)
        {
            break;
        }
        $_index = $index;
    }
    
    echo $_index; //the prev key from 550;
    

    An alternative solution is to get the keys of your array within an enumerated array like so:

    $keys = array_keys($my_array);
    

    as the keys array is index you can move the the previous key like so:

    $required_key = (array_search(550,$keys,true) - 1);
    

    this will fine the value of 550, and return its index within the keys, remove one to get the previous index

    key we have our previous key to get the value from the original array

    $value = $my_array[$required_key];
    
    0 讨论(0)
  • 2020-12-01 07:04

    I solved this issue in this way:

    function getPrevKey($key, $hash = array())
    {
        $keys = array_keys($hash);
        $found_index = array_search($key, $keys);
        if ($found_index === false || $found_index === 0)
            return false;
        return $keys[$found_index-1];
    }
    

    @return previous key or false if no previous key is available

    Example:

    $myhash = array(
        'foo' => 'foovalue',
        'goo' => 'goovalue',
        'moo' => 'moovalue',
        'zoo' => 'zoovalue'
    );
    
    echo "TEST: ". getPrevKey('zoo', $myhash); // prints moo
    
    0 讨论(0)
  • 2020-12-01 07:08

    One option:

    To set the internal pointer to a certain position, you have to forward it (using key and next, maybe do a reset before to make sure you start from the beginning of the array):

    while(key($array) !== $key) next($array);
    

    Then you can use prev():

    $prev_val = prev($array);
    // and to get the key
    $prev_key = key($array);
    

    Depending on what you are going to do with the array afterwards, you might want to reset the internal pointer.

    If the key does not exist in the array, you have an infinite loop, but this could be solved with:

     while(key($array) !== null && key($array) !== $key)
    

    of course prev would not give you the right value anymore but I assume the key you are searching for will be in the array anyway.

    0 讨论(0)
  • 2020-12-01 07:09

    Solution with fast lookups: (if you have to do this more than once)

    $keys = array_flip(array_keys($array));
    $values = array_values($array);
    return $values[$keys[555]-1];
    

    array_flip(array_keys($array)); will return an array mapping keys to their position in the original array, e.g. array(420 => 0, 430 => 1, 555 => 2).

    And array_values() returns an array mapping positions to values, e.g. array(0 => /* value of $array[420] */, ...).

    So $values[$keys[555]-1] effectively returns the previous elements, given that the current one has key 555.

    Alternative solution:

    $keys = array_keys($array);
    return $array[$keys[array_search(555, $keys)-1]];
    
    0 讨论(0)
提交回复
热议问题