PHP get previous array element knowing current array key

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

提交回复
热议问题