我想在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';
请如何运行我的代码来实现此目标
答案 0 :(得分:4)
http://php.net/manual/ro/function.array-search.php
$index = array_search($current_array_val, $array);
if($index !== false && $index > 0 ) $prev = $array[$index-1];
if($index !== false && $index < count($array)-1) $next = $array[$index+1];
答案 1 :(得分:1)
使用next()功能:
另外:使用current()或prev()
$array = array('a', 'b', 'c', 'd', 'e', 'f');
$current= current($array); // 'a'
$nextVal = next($array); // 'b'
$nextVal = next($array); // 'c'
// ...
答案 2 :(得分: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()要慢。我上面描述的方法远更具可扩展性。
答案 3 :(得分:0)
使用array_search,并为数组中的next / prev项增加/减少。
$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
答案 4 :(得分: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();