在数组中的特定值之前和之后获取密钥(在PHP中)

时间:2016-04-19 12:25:09

标签: php

我希望在PHP中获取值beforeafter数组的特定值。

例如我有:

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

我的$specific_value441

在这个例子中,我应该得到之前的(406)和之后的(212)。

如果我的值为212,我应该在之前(441)和之后(314)获得。

4 个答案:

答案 0 :(得分:6)

使用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

答案 1 :(得分:0)

您可以使用array_slice()功能

执行此操作
$input = array("1", "2", "3", "4", "5");

$output = array_slice($input, 2);      // returns "3", "4", and "5"
$output = array_slice($input, -2, 1);  // returns "4"
$output = array_slice($input, 0, 3);   // returns "1", "2", and "3"

对于您的具体示例:

$output = array_slice($input, 2, 4); 
// returns '3' => '4' where 3 is the key and 4 is the value

如果您要查找某个值之前和之后的所有内容,我们将不得不添加另一个名为array_search()的函数

// Get the key for the current value
$key = array_search($currentValue, $array);

// Get everything before the current value
$firstSlice = array_slice($array, -1, $key);

// Get everything after the current value
$secondSlice = array_slice($array, $key);

// Merge the results to one new array
$result = array_merge($firstSlice, $secondSlice);

答案 2 :(得分:0)

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

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;
}

答案 3 :(得分:-1)

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