在PHP数组中获取下一个值

3

我想获取PHP数组中的下一个值,例如:

$array = array('a', 'b', 'c', 'd', 'e', 'f');
$current_array_val = 'c';
//so I want to run a code to get the next value in the array and
$next_array_val = 'd';
//And also another code to get the previous value which will be
$prev_array_val = 'b';

请问如何运行我的代码以实现这个功能。

请仔细查看这个StackOverflow问题以获取详细信息。 - Peter
6个回答

13

如果你正在处理大型数组(array_search() 在大数据集上可能变得相对较慢),可以查看我的使用 array_flip() 方法的答案。 - Jay Welsh

5

使用next()函数:

另外,还可以使用current()或prev()函数。

$array = array('a', 'b', 'c', 'd', 'e', 'f');

$current= current($array); // 'a'
$nextVal = next($array); // 'b'
$nextVal = next($array); // 'c'

// ... 

1
这里是另一种解决方案,
$values = array_values($array);
$search=array_search($current_array_val,$values);
$next=$values[(1+$search)%count($values)];

0
$array = array('a', 'b', 'c', 'd', 'e', 'f');

$flipped_array = array_flip($array);

$middle_letter = 'c'; //Select your middle letter here

$index_of_middle_letter = $flipped_array[$middle_letter];

$next_index = $index_of_middle_letter + 1;
$prev_index = $index_of_middle_letter - 1;
$next_item = $array[$next_index];
$prev_item = $array[$prev_index];

当处理大型数组时,array_search() 比执行 array_flip() 更慢。我上面描述的方法更加可扩展。


0
使用array_search函数,在数组中进行下一个/上一个项目的增量/减量操作。
$array = array('a', 'b', 'c', 'd', 'e', 'f');
$current_array_val = array_search('c', $array);
//so I want to run a code to get the next value in the array and
$next_array_val = $array[$current_array_val+1];
//And also another code to get the previous value which will be
$prev_array_val = $array[$current_array_val-1];


echo $next_array_val; // print d
echo $prev_array_val; // print b

当处理大型数组时,array_search 比进行 array_flip(索引值)要慢。 - Jay Welsh
好的,谢谢你的建议。我不是专业的PHP程序员,只是想通过阅读其他答案来帮助一些人并学习。 - Jax Teller
没问题,兄弟!对于小样本集,你的方法没有任何问题。 :) - Jay Welsh

0

看一下这个代码示例,更好地理解面向对象的数组导航方式:

$array = array('a', 'b', 'c', 'd', 'e', 'f');

$pointer = 'c';

// Create new iterator
$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

$iterator->seek($pointer);     //set position

// Go to the next value
$iterator->next();             // move iterator 

// Assign next value to a variable
$nextValue = $iterator->current();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接