PHP获取前一个数组元素知道当前数组键

Ale*_*tau 29 php arrays

我有一个具有特定键的数组:

array(
    420 => array(...), 
    430 => array(...), 
    555 => array(...)
)
Run Code Online (Sandbox Code Playgroud)

在我的应用程序中,我知道当前的密钥(例如555).我想获得前面的数组元素.在这个例子中,它是带键的数组元素430.我怎么能用PHP做到这一点?我尝试过prev(),但是对于这个函数,我们应该知道当前的数组元素.我没找到函数,设置当前数组元素是什么.

Fel*_*ing 30

一种选择:

要将内部指针设置为某个位置,您必须转发它(使用keynext,可能reset先执行以确保从数组的开头开始):

while(key($array) !== $key) next($array);
Run Code Online (Sandbox Code Playgroud)

然后你可以使用prev():

$prev_val = prev($array);
// and to get the key
$prev_key = key($array);
Run Code Online (Sandbox Code Playgroud)

根据之后您要对数组执行的操作,您可能需要reset内部指针.

如果数组中不存在该键,则会出现无限循环,但这可以通过以下方式解决:

 while(key($array) !== null && key($array) !== $key)
Run Code Online (Sandbox Code Playgroud)

当然prev不会再给你正确的价值,但我认为你要搜索的密钥无论如何都会在数组中.


Arn*_*anc 21

快速查找解决方案:(如果必须多次执行此操作)

$keys = array_flip(array_keys($array));
$values = array_values($array);
return $values[$keys[555]-1];
Run Code Online (Sandbox Code Playgroud)

array_flip(array_keys($array));将返回一个数组映射键到它们在原始数组中的位置,例如array(420 => 0, 430 => 1, 555 => 2).

并且array_values()返回一个数组映射位置到值,例如array(0 => /* value of $array[420] */, ...).

因此$values[$keys[555]-1],假设当前元素具有键555,则有效地返回先前元素.

替代方案:

$keys = array_keys($array);
return $array[$keys[array_search(555, $keys)-1]];
Run Code Online (Sandbox Code Playgroud)


Luc*_*one 7

我用这种方式解决了这个问题:

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];
}
Run Code Online (Sandbox Code Playgroud)

@return前一个键,如果没有以前的键,则返回false

例:

$myhash = array(
    'foo' => 'foovalue',
    'goo' => 'goovalue',
    'moo' => 'moovalue',
    'zoo' => 'zoovalue'
);

echo "TEST: ". getPrevKey('zoo', $myhash); // prints moo
Run Code Online (Sandbox Code Playgroud)


cen*_*enk 5

@Luca Borrione 的解决方案很有帮助。如果你想同时查找上一个和下一个键,你可以使用以下函数:

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;
}
Run Code Online (Sandbox Code Playgroud)

用法:

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

// next key
getAdjascentKey( $key, $hash, +1 );
Run Code Online (Sandbox Code Playgroud)

例子:

$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
Run Code Online (Sandbox Code Playgroud)