Skip to content

Instantly share code, notes, and snippets.

@haxianhe
Created July 25, 2018 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haxianhe/1aaac5f892e5672f53f0a33bc8fe6581 to your computer and use it in GitHub Desktop.
Save haxianhe/1aaac5f892e5672f53f0a33bc8fe6581 to your computer and use it in GitHub Desktop.
查找数组中上一个元素键/值,下一个元素键/值
<?php
/*
* 查找数组中上一个元素键/值,下一个元素键/值
* @param str $currentValue 当前元素的值
* @param array $array 待查询数组
* @return array 上一个元素键/值,下一个元素键/值
*/
public function arrayPrevNext($currentValue, $array)
{
$prev_key = $next_key = null;
$prev_value = $next_value = null;
$findCurrentValue = false;
foreach ($array as $key => $value) {
if ($findCurrentValue) {
$next_key = $key;
$next_value = $value;
break;
}
if ($value == $currentValue) {
$findCurrentValue = true;
} else {
$prev_key = $key;
$prev_value = $value;
}
}
$result = [
'prev_key' => $prev_key,
'prev_value' => $prev_value,
'next_key' => $next_key,
'next_value' => $next_value,
];
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment