[英]How to get Next or Previous Array Value Based On Value PHP
我有这样的代码:
$step_master = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$step_now = 4;
$step_before = ????;
$step_next = ????;
我如何从$step_now
中的$step_master
获取下一个值或上一个值
所以输出应该是这样的:
Now : 4
Previous : 3
Next : 5
我尝试使用next()
但没有$step_now
另一个参数
任何帮助将不胜感激
谢谢
您可以使用array_search
获取当前密钥。 然后迭代到上一步或下一步
$step_master = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$step_now = 4;
$now_index = array_search($step_now,$step_master);
echo "Now = ".$step_now ;
echo "Previous =".(isset($step_master[$now_index - 1])?$step_master[$now_index -1 ] : "");
echo "Next =".(isset($step_master[$now_index +1 ])?$step_master[$now_index +1 ] : "");
$step_master = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$step_now = 4;
$index = array_search($step_now, $step_master);
$step_before = ($index > 0) ? $step_master[$index-1] : null;
$step_next = ($index < count($step_master)) ? $step_master[$index+1] : null;
echo var_dump($step_before, $step_next);
漂亮的老式,但工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.