Created
July 25, 2018 12:46
-
-
Save haxianhe/1aaac5f892e5672f53f0a33bc8fe6581 to your computer and use it in GitHub Desktop.
查找数组中上一个元素键/值,下一个元素键/值
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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