sea*_*987 1 php arrays codeigniter
我有一个看起来像这样的数组,
Array
(
[0] => 849710414
[1] => 849710726
[2] => 849710744
[3] => 849712728
[4] => 849713005
[5] => 849713439
[6] => 849714856
[7] => 849714924
[8] => 849716371
[9] => 849716441
[10] => 849717118
[11] => 849719043
[12] => 849719187
[13] => 849722865
[14] => 849723412
[15] => 849723777
[16] => 849725052
[17] => 849726294
[18] => 849726457
[19] => 849726902
[20] => 849728239
[21] => 849728372
[22] => 849728449
[23] => 849730353
[24] => 849733625
)
Run Code Online (Sandbox Code Playgroud)
这些是我需要添加到URL以在网站中导航的ID,ID是从用户的搜索返回的结果,然后用户点击搜索结果并且可以选择转到下一个搜索结果看看前一个,现在我虽然通过这样做可以做到这一点
<a href="<?=next($array);?>">Next</a>
<a href="<?=prev($array);?>">Prev</a>
Run Code Online (Sandbox Code Playgroud)
我怎么似乎都没有意识到我正在看的当前结果ID是什么,以及下一个和之前的工作?现在有人如何解决这个问题?
您需要做的是找出您当前正在查看的数组的索引,(array_search())然后添加1以获取下一个值,并减去1以获取先前的值.
// Find the index of the current item
$current_index = array_search($current_id, $array);
// Find the index of the next/prev items
$next = $current_index + 1;
$prev = $current_index - 1;
Run Code Online (Sandbox Code Playgroud)
你的HTML:
<?php if ($prev > 0): ?>
<a href="<?= $array[$prev] ?>">Previous</a>
<?php endif; ?>
<?php if ($next < count($array)): ?>
<a href="<?= $array[$next] ?>">Next</a>
<?php endif; ?>
Run Code Online (Sandbox Code Playgroud)