php数组查找上一条与下一条

<?php
// 其实foreach是改变指针(下一个)的,找到当前键值,可以用prev, next
function prevNext($index, $arr) {
    $next_key = $prev_key = null;
    foreach ($arr as $key =>  $v) {
        if ($next) {
            $next_key = $v;
            break;
        }
        if ($key == $index){
            $next = true;
          } else {
            $prev_key = $v;
          }
    }
    return array('prev_key' => $prev_key, 'next_key' => $next_key);
}
$arr = array(4=>4,6=>6,9=>9,5=>5);
var_dump(prevNext(6, $arr));


//private function _findPrevNext(&$datas, $key, &$prev_subject, &$next_subject) {
//    if(!$datas) return array();
//    current($datas);
//    $first = key($datas);
//    while (key($datas) != $key) {
//        next($datas);
//    }
//    if(key($datas) == $first) {
//        $prev_subject = false;
//    } else {
//        prev($datas);
//        $prev_subject = key($datas);
//        next($datas);
//    }
//    next($datas);
//    $next_subject = key($datas);
//}
?>

你可能感兴趣的:(php数组查找上一条与下一条)