簡體   English   中英

如何基於值PHP獲取下一個或上一個數組值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM