获取数组中特定值前后的键(在PHP中)


Get keys before and after specific value in array (in PHP)

我想得到值beforeafter,它们是PHP中数组的特定值。

例如,我有:

$array = (441, 212, 314, 406);

我的$specific_value就是441

在这个例子中,我应该得到before(406)和after(212)。

如果我的值是212,我应该得到之前(441)和之后(314)。

使用array_search函数的解决方案:

$array = [441, 212, 314, 406];
$val = 441;
$currentKey = array_search($val, $array);
$before = isset($array[$currentKey - 1]) ? $array[$currentKey - 1] : $array[count($array) - 1];
$after = isset($array[$currentKey + 1]) ? $array[$currentKey + 1] : $array[0];
var_dump($before, $after);

输出:

int(406)
int(212)

http://php.net/manual/en/function.array-search.php

$key = array_search ('441', $arr);
$beforeKey = $key-1;
if($beforeKey<1)
{ $beforeKey = count($array)-1; }
$afterKey = $key+1;
$beforeValue = $array[$beforeKey];
$afterValue = $array[$afterKey];

对于搜索后的递归键,可能需要这样的东西:

function get_all_after_array_key($array,$key){
	$currentKey = array_search($key, array_keys($array));
	$hasNextKey = (isset($array[$currentKey + 1])) ? TRUE : FALSE;
	$array = array_keys($array);
	$after = [];
	do {
		if(isset($array[$currentKey + 1])) {
			$hasNextKey = TRUE;
			$after[] = $array[$currentKey + 1];
			$currentKey = $currentKey + 1;
		} else {
			$hasNextKey = FALSE;
		}
	} while($hasNextKey == TRUE);
    return $after;
}