PHP:如果是last / first,使用循环获取数组的next / prev元素

时间:2015-09-22 11:59:58

标签: php arrays navigation

我无法在我的投资组合中添加导航箭头。我想基于当前的id得到next和prev id。问题是当$current_id是数组的最后一个时,我不知道如何去第一个创建一种循环。如果$current_id是第一个元素,那么如何将最后一个元素设为prev?我被困了,你能帮我吗?

这是我的代码:

<?php 

    $current_id = "10";

    $array = array(
        "1" => "aa",
        "2" => "bb",
        "3" => "cc",
        "4" => "dd",
        "5" => "ee",
        "6" => "ff",
        "7" => "gg",
        "8" => "hh",
        "9" => "ii",
        "10" => "jj",
    );


    $current_index = array_search($current_id, $array);

    $next = $current_index + 1;
    $prev = $current_index - 1;

?>

4 个答案:

答案 0 :(得分:2)

您可以使用模%作为下一个值:

$number_of_elements = count($array);
$next = ($current_index + 1) % $number_of_elements;

对于prev值而言是if,因为modulo不喜欢负数

$prev = $current_index - 1
if ($prev < 0){
    $prev = $number_of_elements - 1;
}

答案 1 :(得分:1)

以这种方式使用模数:

$current_id = 9;

$array = array(
    "aa",
    "bb",
    "cc",
    "dd",
    "ee",
    "ff",
    "gg",
    "hh",
    "ii",
     "jj",
);

$next = ($current_id+($count=count($array))+1)%$count;
$previous = ($current_id+$count-1)%$count;

print("$previous $next");

答案 2 :(得分:0)

您可以使用reset()end()函数将数组指针移动到数组的开头和结尾。因此,在处理数组之前,您可以执行以下操作:

end($array);
$end = key($array);

然后:

reset ($array);
while (current ($array)) {
    $current_index = key($array);
    $current_value = current($array);
    if ($current_index == $end) 
        reset($array);
    else
        next($array);
}

或者,构建某种链表,其中数组的每个元素都有一个指向下一个元素的指针/引用。

答案 3 :(得分:0)

如果您的页面的最后一个ID,则可以实现它。

尝试

 ExecutorService executor = Executors.newFixedThreadPool(10);
 Runnable firstWorker = new DataComparison(DataComparison.FIRST_THREAD_INSTANCE,args[0], args[1], args[2], runSkey, fic_mis_date,legal_entity, args[6],failover);


 Runnable secondWorker = new DataComparison(DataComparison.SECOND_THREAD_INSTANCE,args[0], args[1], args[2], runSkey, fic_mis_date,legal_entity, args[6],failover);


  Runnable thirdWorker = new DataComparison(DataComparison.THIRD_THREAD_INSTANCE,args[0], args[1], args[2], runSkey, fic_mis_date,legal_entity, args[6],failover);

 CompletableFuture firstTask = CompletableFuture.runAsync(firstWorker,
          executor);
 firstTask.thenRunAsync(secondWorker,executor)
 firstTask.thenRunAsync(thirdWorker,executor);