简体   繁体   English

使用post数据的数组搜索获取数组中的下一个元素

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

Each time I click the next button it's stuck up in the 1st element that has been search in the array. 每次我点击下一个按钮时,它都会在第一个已经在数组中搜索的元素中出现。 Here's my sample code: 这是我的示例代码:

<?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>

The output is: 输出是:

B

My desired output is: 我想要的输出是:

A-> B-> C-> D

how to go to every next element everytime I click the next button & if the last element shown I want it to go to the 1st element in the array like it was loop to the 1st element. 每次单击下一个按钮时如何转到每个下一个元素&如果显示的最后一个元素我希望它转到数组中的第一个元素,就像它循环到第一个元素一样。 I don't want to use a $_GET I want a $_POST. 我不想使用$ _GET我想要$ _POST。 Kindly help me out this one? 请帮我解决这个问题? Thank you. 谢谢。

Try this. 试试这个。 You need to post the variable back to the script so that upon each page load, it can know what the previous value was. 您需要将变量发布回脚本,以便在每次加载页面时,它可以知道之前的值是什么。

<?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>

Edit : Have added a check on the index variable $get to only increment if it is not at the end of the array, otherwise it should reset. 编辑 :已添加对索引变量$get的检查,如果它不在数组末尾,则仅增加,否则应重置。

Try this. 试试这个。 We are passing the current letter as a hidden post variable. 我们将当前字母作为隐藏的后置变量传递。

<?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