PHP: 获取数组的 next/prev 元素如果 last/first 循环
PHP: Get next/prev element of an array with loop if last/first
我没能在我的投资组合中添加导航箭头。我想根据当前 ID 获取下一个和上一个 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;
?>
您可以对下一个值使用模 %
:
$number_of_elements = count($array);
$next = ($current_index + 1) % $number_of_elements;
以及前一个值的 if,因为模数不喜欢负数
$prev = $current_index - 1
if ($prev < 0){
$prev = $number_of_elements - 1;
}
您可以使用 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);
}
或者,构建某种链表,其中数组的每个元素都会有一个 pointer/reference 到下一个元素。
以这种方式使用模数:
$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");
如果您有页面的最后一个 ID,您就可以实现它。
试试
$last=count($array);
$next = $current_index + 1;
$next=$next<0?$last:$next;
$prev = $current_index - 1;
$prev =$prev==$last?1:$prev
我没能在我的投资组合中添加导航箭头。我想根据当前 ID 获取下一个和上一个 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;
?>
您可以对下一个值使用模 %
:
$number_of_elements = count($array);
$next = ($current_index + 1) % $number_of_elements;
以及前一个值的 if,因为模数不喜欢负数
$prev = $current_index - 1
if ($prev < 0){
$prev = $number_of_elements - 1;
}
您可以使用 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);
}
或者,构建某种链表,其中数组的每个元素都会有一个 pointer/reference 到下一个元素。
以这种方式使用模数:
$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");
如果您有页面的最后一个 ID,您就可以实现它。
试试
$last=count($array);
$next = $current_index + 1;
$next=$next<0?$last:$next;
$prev = $current_index - 1;
$prev =$prev==$last?1:$prev