簡體   English   中英

使用post數據的數組搜索獲取數組中的下一個元素

[英]Array search with post data get next element in the array

每次我點擊下一個按鈕時,它都會在第一個已經在數組中搜索的元素中出現。 這是我的示例代碼:

<?php

$letter = 'A';

if (isset($_POST["next"])) 
{
    if(isset($next))
    {
        unset($letter);
        $letter = $next;
    }

    $alphabet = array('A', 'B', 'C', 'D', 'E');

    $get = array_search($letter, $alphabet);

    $next = $alphabet[$get + 1];

    echo $next;
}

?>

<form name="alphabet" method="post"> 
<input type="submit"  name="next" value="next"/>
</form>

輸出是:

B

我想要的輸出是:

A-> B-> C-> D

每次單擊下一個按鈕時如何轉到每個下一個元素&如果顯示的最后一個元素我希望它轉到數組中的第一個元素,就像它循環到第一個元素一樣。 我不想使用$ _GET我想要$ _POST。 請幫我解決這個問題? 謝謝。

試試這個。 您需要將變量發布回腳本,以便在每次加載頁面時,它可以知道之前的值是什么。

<?php
        $letter = 'A';

        if (isset($_POST["letter"]))
        {
            $letter = $_POST["letter"];

            $alphabet = array('A', 'B', 'C', 'D', 'E');

            $get = array_search($letter, $alphabet);

            if($get < (count($alphabet) - 1))
            {
                $get++;
            }
            else
            {
                $get = 0;
            }

            $letter = $alphabet[$get];

            echo $letter;
        }

        ?>

        <form name="alphabet" method="post">
            <input type="hidden"  name="letter" value="<?php echo $letter ?>" />
            <input type="submit"  value="next" />
        </form>

編輯 :已添加對索引變量$get的檢查,如果它不在數組末尾,則僅增加,否則應重置。

試試這個。 我們將當前字母作為隱藏的后置變量傳遞。

<?php

$alphabet = array('A', 'B', 'C', 'D', 'E');
$next = 'A';   //for the first call of page.
if (isset($_POST["next"])) 
{

    $letter = $_POST['letter'];

    $get = array_search($letter, $alphabet);

    $next = $alphabet[($get + 1)%count($alphabet)];  //for loop over array

}

echo $next;
?>

<form name="alphabet" method="post"> 
<input type="hidden"  name="letter" value="<?php echo $next;?>"/>
<input type="submit"  name="next" value="next"/>
</form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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