简体   繁体   English

获取php数组中的下一个值

[英]get next value in php array

I have an array where I want to get the next value. 我有一个数组,我想获取下一个值。

$sorting = array(0 => "H 101", 1 => "S 101", 2 => "R 172", 3 => "D 141", 4 => "T 101", 5 => "K 101", 6 => "A 182", 7 => "G 101");

I have the current value taken from a SELECT statement. 我有从SELECT语句中获取的当前值。 I have tried array_search but I can't get it to do want I want. 我已经试过array_search,但我无法做到我想要的。

Let's say my current value is S 101, how can I get it to give me "R 172" as the next value which I then can use in a new SELECT statement. 假设我的当前值为S 101,如何得到它给我“ R 172”作为下一个值,然后可以在新的SELECT语句中使用它。

And I also want it to get back to the first value (H 101) if the current value is the last (G 101). 如果当前值是最后一个值(G 101),我还希望它返回到第一个值(H 101)。

next() and prev() deal with the internal pointer of the array while your script is processing. 在脚本处理过程中,next()和prev()处理数组的内部指针。

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

// Find the index of the next/prev items
$next = $current_index + 1;
$prev = $current_index - 1;

Your HTML: 您的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; ?>

Why have you explicitly specified the indices? 为什么要明确指定索引? These would be the same had you not done it. 如果您不这样做,这些将是相同的。

From what I understand, array_search would be suitable for what you want. 据我了解,array_search将适合您的需求。

$current = 'S 101';
$nextkey = array_search($current, $sorting) + 1;
if($nextkey == count($sorting)) {
    // reached end of array, reset
    $nextkey = 0;
}

$next = $sorting[$nextkey];

HOWEVER, if I understand you correctly you're looping through this array and making queries on it. 但是,如果我对您的理解正确,那么您正在遍历此数组并对其进行查询。 How about posting what you want in terms of query result, as there may be a better solution (ie MySQL IN() ) 如何发布查询结果方面的内容,因为可能会有更好的解决方案(例如MySQL IN()

Operationally you could retrive the index of your current value in that way 在操作上,您可以通过这种方式检索当前值的索引

$key = array_search($currValue, $sorting);

Then you should do myNewValue = $sorting[($key+1)%8] or if you don't know the size of array, you have to do myNewValue = $sorting[($key+1)%(count($sorting)+1)] 然后,您应该执行myNewValue = $sorting[($key+1)%8]或者,如果您不知道数组的大小,则必须执行myNewValue = $sorting[($key+1)%(count($sorting)+1)]

Assuming you know you're not going to go off the end of your array and that your input exists: 假设您知道不会离开数组的末尾并且输入存在:

$sorting = array(0 => "H 101", 1 => "S 101", 2 => "R 172", 3 => "D 141", 4 => "T 101", 5 => "K 101", 6 => "A 182", 7 => "G 101");

$key = array_search("H 101", $sorting);
$returnValue = $sorting[$key + 1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM